Home >Backend Development >C++ >How to Deserialize XML into Objects using XmlSerializer in C#?

How to Deserialize XML into Objects using XmlSerializer in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-15 16:06:44487browse

How to Deserialize XML into Objects using XmlSerializer in C#?

Use C# XmlSerializer to deserialize XML into objects

This article introduces how to use C#'s XmlSerializer class to deserialize XML data into objects. This requires you to define a C# class that matches the XML structure. The steps are as follows:

  1. Create matching class structure:

First, create a class corresponding to the XML root element. For example, if the root element of XML is <StepList>, create a class named StepList:

<code class="language-csharp">[XmlRoot("StepList")]
public class StepList
{
    // ...
}</code>
  1. Add attributes:

Next, add the corresponding attributes to the class for each child element in the XML. Use the XmlElement attribute to specify element names. For example:

<code class="language-csharp">public class Step
{
    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("Desc")]
    public string Desc { get; set; }
}</code>
  1. Deserialize using XmlSerializer:

Finally, use XmlSerializer to deserialize the XML into an object:

<code class="language-csharp">XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(xmlString)) // xmlString 为您的XML字符串
{
    StepList result = (StepList)serializer.Deserialize(reader);
}</code>

Based on the XML example provided, a suitable class structure is as follows:

<code class="language-csharp">[XmlRoot("StepList")]
public class StepList
{
    [XmlElement("Step")]
    public List<Step> Steps { get; set; }
}

public class Step
{
    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("Desc")]
    public string Desc { get; set; }
}</code>

Through the above steps, you can easily map XML data to C# objects to facilitate subsequent processing and use.

The above is the detailed content of How to Deserialize XML into Objects using XmlSerializer in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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