Home > Backend Development > C++ > How to Deserialize an XML Document into C# Objects?

How to Deserialize an XML Document into C# Objects?

DDD
Release: 2025-02-02 17:16:09
Original
808 people have browsed it

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:

<?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>
Copy after login

To deserialize this, we create matching C# classes:

[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; }
}
Copy after login

Now, we can deserialize the XML using XmlSerializer:

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);
}
Copy after login

Remember to replace xmlFilePath with the actual path to your XML file.

Alternatively, you can use a two-step process involving XSD:

  1. Generate XSD: Create an XML Schema Definition (XSD) from your XML file using an appropriate tool (many IDEs offer this functionality).

  2. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template