Groups | Blog | Home
all groups > dotnet xml > february 2005 >

dotnet xml : Create an XmlDocument from XmlSerializer?


Raterus
2/23/2005 4:38:45 PM
Hello,

This is probably a very simple question. I played around with it some =
but couldn't get it.

I'm got a custom class I'm serializing, I'm loading the results into a =
new XmlDocument. What is the best way to take the results from the =
XmlSerializer and convert it into an XmlDocument. I'm guessing the best =
way to accomplish this is through streams.

Can someone point me in the right direction as to the best way to do =
this? I can serialize the class to a file, then load the file, but that =
is like going around my elbow to get to my thumb!, there has to be a =
better way!

Thanks,
Derek Harmon
2/23/2005 9:15:32 PM
[quoted text, click to view]

Create an empty XmlDocument, like this

XmlDocument doc = new XmlDocument( );

then use Chris Lovett's XmlNodeWriter [1] to wrap the XmlDocument and
pipe the serialization calls to it through Serialize( )'s XmlWriter argument,

serializer.Serialize( obj, new XmlNodeWriter( doc) );

[quoted text, click to view]

If you don't like using the XmlNodeWriter then alternatively, you can
dispatch with the File altogether and serialize to a String or Memory-
Stream (take your choice; everybody has their favorite) and wrap
that in a StringWriter / StreamWriter to pipe the results through the
Serialize( )'s TextWriter argument.

Then use doc.LoadXml( ) or re-set the Position of your Memory-
Stream to 0 and then use doc.Load( new StreamReader( ms) ) on
it.

Dispatching with the File makes this more like going around your
wrist to get to your thumb.

XmlNodeWriter should be present in the System.Xml namespace of
..NET 2.0 (present as of Beta 1; can't imagine it'd get pulled though),
so if your application targets 2.0 it'll simplify matters greatly for you.


Derek Harmon
___
[1] - Chris Lovett's XmlNodeWriter on GotDotNet
http://www.gotdotnet.com/community/usersamples/Default.aspx?query=XmlNodeWriter

Raterus
2/25/2005 9:54:47 AM
Thanks, that's exactly what I needed. It's good to know this gets a =
little easier in 2.0!
--Michael

[quoted text, click to view]
http://www.gotdotnet.com/community/usersamples/Default.aspx?query=3DXmlNo=
deWriter
[quoted text, click to view]
AddThis Social Bookmark Button