Sunday, June 8, 2014

Xml to Object

I have xml as datasource and need to be translated to an object. Sometimes the xml is not in desirable structure and we can’t compromise with it. Here are few example of xml and class definition for them. Example:
  1. <catalog>
  2. <item>
  3. <id>18338517</id>
  4. <note label="Name ">Gear xyz</note>
  5. <note label="Size ">10</note>
  6. <note label="Source">Store xyz</note>
  7. <relation weight="100">
  8. <type>External</type>
  9. <id>123</id>
  10. <name>Mcday</name>
  11. </relation>
  12. <relation weight="99">
  13. <type>Internal</type>
  14. <id>234</id>
  15. <name>Mcnight</name>
  16. </relation>
  17. </item>
  18. <item> ..... </item>
  19. </catalog>

Following are the class definition:
  1. [XmlRoot("catalog")]
  2. public class Catalog
  3. {
  4.     [XmlElement("item")]
  5.     public Item[] item{ get; set; }
  6. }
  7. [XmlType("item")]
  8. public class Item
  9. {
  10.     [XmlElement("id")]
  11.     public string id { get; set; }
  12.     [XmlElement("note", typeof(Note))]
  13.     public Note[] note { get; set; }
  14.     [XmlElement("relation", typeof(Relation))]
  15.     public Relation[] relation { get; set; }
  16. }
  17. [Serializable]
  18. public class Note
  19. {
  20.     [XmlAttribute("label")]
  21.     public string label { get; set; }
  22.     [XmlText]
  23.     public string Value { get; set; }
  24. }
  25. [Serializable]
  26. public class Relation
  27. {
  28.     [XmlAttribute("weight")]
  29.     public string weight { get; set; }
  30.     [XmlText]
  31.     public string Value { get; set; }
  32.     [XmlElement("id")]
  33.     public string id { get; set; }
  34.     [XmlElement("type")]
  35.     public string type { get; set; }
  36.     [XmlElement("name")]
  37.     public string name { get; set; }
  38. }

Finally deserializing xml:
  1. Catalog catalog = null;
  2. XmlSerializer mySerializer = new XmlSerializer(typeof(Catalog));
  3. using (TextReader reader = new StreamReader(@"C:\xml\catalog.xml"))
  4. {
  5. catalog = (Catalog)mySerializer.Deserialize(reader);
  6. }

Note:
  • For xml tag that don’t have any attribute and inner tag, but have value, we can just put it as below
    1. [XmlElement("id")]
    2. public string id { get; set; }
  • For xml tag that have attribute and value, we can refer to Note as example
References http://msdn.microsoft.com/en-us/library/2baksw0z(v=vs.110).aspx http://stackoverflow.com/questions/22781813/missing-child-nodes-when-deserializing-xml-to-object

No comments: