Home >Backend Development >C++ >How to Deserialize an XML Document into C# Objects?
C# XML Deserialization: Transforming XML Data into Objects
This guide demonstrates how to convert XML documents into C# objects, a process known as deserialization. Let's use this sample XML:
<code class="language-xml"><?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></code>
To deserialize this, we create matching C# classes:
<code class="language-csharp">[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; } }</code>
Now, we can deserialize the XML using XmlSerializer
:
<code class="language-csharp">XmlSerializer serializer = new XmlSerializer(typeof(Cars)); Cars carData; using (XmlReader reader = XmlReader.Create(xmlFilePath)) // xmlFilePath should be replaced with the actual file path { carData = (Cars)serializer.Deserialize(reader); }</code>
Remember to replace xmlFilePath
with the actual path to your XML file.
Alternatively, you can use a two-step process involving XSD:
Generate XSD: Create an XML Schema Definition (XSD) from your XML file using an appropriate tool (many IDEs offer this functionality).
Generate C# Classes from XSD: Use the xsd.exe
command-line tool (included with Visual Studio) with the /classes
option to generate C# classes from the XSD. This will automatically create classes mirroring your XML structure. Then, use the XmlSerializer
as shown above. This method is particularly useful for complex XML structures.
The above is the detailed content of How to Deserialize an XML Document into C# Objects?. For more information, please follow other related articles on the PHP Chinese website!