Tuesday, 24 July 2012

Parse XML to object model in C# using XSD utility

* Run xsd Visual Studio command line utility to generate object from xsd file (from Visual Studio Command Prompt)

xsd-util
* Then add the cs file to your project (same place as your xsd file)
xsd-contacts
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="urn:contacts"
    xmlns:bks="urn:contacts">
 
  <xsd:element name="contacts" type="bks:Contacts"/>
 
  <xsd:complexType name="Contacts">
    <xsd:sequence>
      <xsd:element name="contact"
        type="bks:Contact"
        minOccurs="0"
        maxOccurs="unbounded"/>
  </xsd:sequence>
  </xsd:complexType>
 
  <xsd:complexType name="Contact">
  <xsd:sequence>
    <xsd:element name="firstName" type="xsd:string"/>
    <xsd:element name="lastName"  type="xsd:string"/>    
    <xsd:element name="age"     type="xsd:int" />
    <xsd:element name="dob"     type="xsd:date" />
    <xsd:element name="salary"  type="xsd:float" />
  </xsd:sequence>
  <xsd:attribute name="id"   type="xsd:int"/>
  </xsd:complexType>
</xsd:schema>
<?xml version="1.0" encoding="utf-8" ?>
<contacts>
  <contact id='1'>
    <firstName>Michael</firstName>
    <lastName>Jordan</lastName>
    <age>40</age>
    <dob>1965</dob>
    <salary>100.35</salary>
  </contact>
  <contact id='2'>
    <firstName>Scottie</firstName>
    <lastName>Pippen</lastName>
    <age>38</age>
    <dob>1967</dob>
    <salary>55.28</salary>
  </contact>
</contacts>
[Test]
public void Test()
{
  Contacts contacts = null;
 
  var xRoot = new XmlRootAttribute();
  xRoot.ElementName = "contacts";
  //xRoot.Namespace = "http://<if you need one>";
  xRoot.IsNullable = true;
 
  var serializer = new XmlSerializer(typeof(Contacts), xRoot);
 
  using (TextReader reader = new StreamReader(@"contacts.xml"))
  {
    contacts = (Contacts)serializer.Deserialize(reader);
  }
 
  Console.WriteLine(contacts.contact.Count());
  Console.WriteLine(contacts.contact[0].firstName);
  Console.WriteLine(contacts.contact[0].id);
}

1 comment:

Unknown said...

Hi!

While I tried to run this code it gave me error
There is an error in XML document (1, 40).

Post a Comment