Home > Backend Development > C++ > How to Deserialize XML into C# Classes?

How to Deserialize XML into C# Classes?

Patricia Arquette
Release: 2025-02-02 17:26:13
Original
921 people have browsed it

How to Deserialize XML into C# Classes?

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.
  1. [Serializable] Create a derivative logic: [XmlElement] Implement a method, and the XML document is serialized into the instance of the
  2. class.
<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>
Copy after login
  1. Alternative method: 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>
Copy after login
Save the XML file to the disk as

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
  • is replaced with your actual XML file path.

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!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template