- <catalog>
- <item>
- <id>18338517</id>
- <note label="Name ">Gear xyz</note>
- <note label="Size ">10</note>
- <note label="Source">Store xyz</note>
- <relation weight="100">
- <type>External</type>
- <id>123</id>
- <name>Mcday</name>
- </relation>
- <relation weight="99">
- <type>Internal</type>
- <id>234</id>
- <name>Mcnight</name>
- </relation>
- </item>
- <item> ..... </item>
- </catalog>
Following are the class definition:
- [XmlRoot("catalog")]
- public class Catalog
- {
- [XmlElement("item")]
- public Item[] item{ get; set; }
- }
- [XmlType("item")]
- public class Item
- {
- [XmlElement("id")]
- public string id { get; set; }
- [XmlElement("note", typeof(Note))]
- public Note[] note { get; set; }
- [XmlElement("relation", typeof(Relation))]
- public Relation[] relation { get; set; }
- }
- [Serializable]
- public class Note
- {
- [XmlAttribute("label")]
- public string label { get; set; }
- [XmlText]
- public string Value { get; set; }
- }
- [Serializable]
- public class Relation
- {
- [XmlAttribute("weight")]
- public string weight { get; set; }
- [XmlText]
- public string Value { get; set; }
- [XmlElement("id")]
- public string id { get; set; }
- [XmlElement("type")]
- public string type { get; set; }
- [XmlElement("name")]
- public string name { get; set; }
- }
Finally deserializing xml:
- Catalog catalog = null;
- XmlSerializer mySerializer = new XmlSerializer(typeof(Catalog));
- using (TextReader reader = new StreamReader(@"C:\xml\catalog.xml"))
- {
- catalog = (Catalog)mySerializer.Deserialize(reader);
- }
Note:
- For xml tag that don’t have any attribute and inner tag, but have value, we can just put it as below
- [XmlElement("id")]
- public string id { get; set; }
- For xml tag that have attribute and value, we can refer to Note as example
No comments:
Post a Comment