2

I've been using Linq To XML in order to mapp the XML DOcument to .NET OBjects.

Could anyone please guide me whether there any too exist where I can pass XML Document (string) and it returns strongly Type .NET OBject?

I've been looking at XSD2Code and having a problem passing the whole XML as it seems to create separate classes for each Elements.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Nil Pun
  • 17,035
  • 39
  • 172
  • 294

2 Answers2

3

Pretty easy:

  1. take your XML and run it through the xsd.exe command line tool:

    c:\> xsd.exe yourfile.xml
    

    This will produce a corresponding XML schema file (yourfile.xsd)

  2. Run the xsd.exe tool again, this time on the XSD file, to get a C# class:

    c:\> xsd.exe /c yourfile.xsd
    

    This will produce a C# class in yourfile.cs which represents your XML content

  3. Using that class in a project, just deserialize your XML into a C# object:

    XmlSerializer ser = new XmlSerializer(typeof(YourClass));
    
    var result = ser.Deserialize(new FileStream(@"D:\temp\yourfile.xml", FileMode.Open));
    

    If everything worked as it should, your result now contains a C# class instance that represents 1:1 that XML file's content.

That's it!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Thanks @marc_s, What I'm after is how to deserialize the XML Document and get strongly typed .NET Object. – Nil Pun Aug 12 '11 at 06:37
  • @Myagdi I guess you mean type safety. Unfortunately we don't have an `XmlSerializer` that returns T on `Deserialize()` so you have to cast from `object` to `T` yourself. I still wonder why they didn't introduced that with generics in .net2. – mbx Nov 05 '13 at 14:25
0

Just use the xsd util.

IIRC, you call it xsd /c yourschema.xsd > classes.cs.

If you have a bunch of XML without schema, you can also use xsd to try infer a schema. That should be a good starting point anyways :)

leppie
  • 115,091
  • 17
  • 196
  • 297