0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
1110
  • 7,829
  • 55
  • 176
  • 334

1 Answers1

2

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);
}
LunicLynx
  • 939
  • 1
  • 8
  • 16
  • Thanks. Just one sub question as I didn't know until today just to confirm. I received XSD file and used xsd.exe to get cs class now when I receive XML and serialize it like you write in answer all data in that class should be populated like when use ORM? – 1110 Aug 14 '13 at 17:37
  • If you mean ORM in Object Relational Mapper then yes, if you compare it to an ORM in a DB sense then i would say no since there is no comparable capability like delete or update without rewriting the whole file. – LunicLynx Aug 14 '13 at 17:46
  • Also i would question the whole approach of going from XmlDocument to XmlSerializer. This only makes sense as long as you really can't change how that function you mention is invoked. (not able to change the signature) – LunicLynx Aug 14 '13 at 17:47
  • Thanks when I say like ORM I thought just on populate properties of generated classes. I choose XmlSerializer because I have just XSD and have no idea what everything can get in (as it's large XSD). I just need to get all data that provider sent me store somewhere in a code and store that in database. – 1110 Aug 14 '13 at 19:46