Search code examples
c#xml-serializationxmldocumentxmlserializerxsd.exe

How to use XmlDocument object instead of reading XML file from drive?


I didn't know that I can use XSD schema to serialize received XML file. I used xsd.exe to generate cs class from XSD file and now I need to use that class to get data in class properties but I miss one thing and I need help.

This is the code:

private void ParseDataFromXmlDocument_UsingSerializerClass(XmlDocument doc)
{
XmlSerializer ser = new XmlSerializer(typeof(ClassFromXsd));

            string filename = Path.Combine("C:\\myxmls\\test", "xmlname.xml");

            ClassFromXsdmyClass = ser.Deserialize(new FileStream(filename, FileMode.Open)) as ClassFromXsd;

            if (myClass != null)
            {
                // to do
            }
...

Here I use XML file from drive. And I want to use this XmlDocument from parameter that I passed in. So how to adapt this code to use doc instead XML from drive?


Solution

  • You could write the XmlDocument to a MemoryStream, and then Deserialize it like you already did.

    XmlDocument doc = new XmlDocument();
    ClassFromXsd obj = null;
    using (var s = new MemoryStream())
    {
        doc.Save(s);
        var ser = new XmlSerializer(typeof (ClassFromXsd));
        s.Seek(0, SeekOrigin.Begin);
        obj = (ClassFromXsd)ser.Deserialize(s);
    }