C# XML Revitalization: Full Guide
Background:
Revitalization refers to the process of converting serialized data back to its original object format. This article provides a complete guide to introduce how to discern the XML document into a custom C#class that indicates the XML structure.
Revitalization process:
Define the class structure: Create C#class that reflects the XML document structure. Use
and to map the XML element to the class attribute.[Serializable]
Create a derivative logic: [XmlElement]
Implement a method, and the XML document is serialized into the instance of the <code class="language-csharp">[Serializable()] public class Car { [XmlElementAttribute("StockNumber")] public string StockNumber { get; set; } [XmlElementAttribute("Make")] public string Make { get; set; } [XmlElementAttribute("Model")] public string Model { get; set; } } [XmlRootAttribute("Cars", IsNullable = false)] public class Cars { [XmlArrayItem(typeof(Car))] public Car[] Car { get; set; } }</code>
Cars
Another method is to use XSD (XML mode definition) to generate C#class that conforms to the XML structure. <code class="language-csharp">public class CarSerializer { public Cars Deserialize(string path) { // 读取XML文件 XmlSerializer serializer = new XmlSerializer(typeof(Cars)); using (StreamReader reader = new StreamReader(path)) { // 将XML反序列化到Cars对象 return (Cars)serializer.Deserialize(reader); } } }</code>
Generate XSD mode:
Generate C#code:
foo.xml
This will create , which contains the C#class with the XML structure. xsd foo.xml
Use alternative implementation: xsd foo.xsd /classes
Through the above steps, you can easily dissection XML data into the C#object to facilitate subsequent processing and use. Please note that The above is the detailed content of How to Deserialize XML into C# Classes?. For more information, please follow other related articles on the PHP Chinese website!