Example XML document
<?xml version="1.0" encoding="utf-8"?><cars><car><stocknumber>1020</stocknumber><make>Nissan</make><model>Sentra</model></car><car><stocknumber>1010</stocknumber><make>Toyota</make><model>Corolla</model></car><car><stocknumber>1111</stocknumber><make>Honda</make><model>Accord</model></car></cars>
[Serializable()] public class Car { [System.Xml.Serialization.XmlElementAttribute("StockNumber")] public string StockNumber{ get; set; } [System.Xml.Serialization.XmlElementAttribute("Make")] public string Make{ get; set; } [System.Xml.Serialization.XmlElementAttribute("Model")] public string Model{ get; set; } }
[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)] public class Cars { [XmlArrayItem(typeof(Car))] public Car[] Car { get; set; } }
This method loads the XML document, uses XMLSerializer to convert it to a CARS object, and returns a counter serialized data.
public class CarSerializer { public Cars Deserialize() { string path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data/") + "cars.xml"; using (XmlReader reader = XmlReader.Create(path)) { XmlSerializer ser = new XmlSerializer(typeof(Cars)); Cars cars = (Cars)ser.Deserialize(reader); return cars; } } }
Using the data of the carrier -oriented data
The above is the detailed content of How to Deserialize XML Documents into C# Objects?. For more information, please follow other related articles on the PHP Chinese website!