Paul Thompson
Developer for Hire

Quick and painless XML with XSD and XMLSerializer

I spend 1/2 of my day last week banging my head against a wall, trying to parse a long XML document into a CLR object. I tried XPATH, DOM, etc, but they kept running into snags when trying to iterate multiple values, etc. So the following solution allowed me to take the XML our billing company POSTs to me, and make it into a CLR object that I can use in code very easily.

  • Get the XSD for the XML – fortunately, my billing company provides it, otherwise, xsd can convert the xml to xsd.
  • xsd file.xsd /c /o:dest/path
  • use the XMLSerialize class to take the POSTed XML and put it into the generated CS class from XSD:

XmlSerializer deserializer = new XmlSerializer(typeof(GENERATED.CS));
TextReader textReader = new StreamReader(Request.InputStream);
GENERATED response = (GENERATED.CS)deserializer.Deserialize(textReader);

There you are, the GENERATED class’s object now contains all of the data from the XML in a CLR accessable manner!



Your Cart