Home >Backend Development >C++ >How to Effectively Deserialize XML Data into C# Objects?

How to Effectively Deserialize XML Data into C# Objects?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-15 16:12:44666browse

How to Effectively Deserialize XML Data into C# Objects?

C# XML Deserialization: A Complete Guide

Deserializing XML data into objects is a critical step in accessing and processing structured information in a variety of applications. This article will dive into how to build classes for successful XML deserialization.

Build classes for deserialization

Consider the following XML example:

<code class="language-xml"><steplist><step><name>Name1</name><desc>Desc1</desc></step><step><name>Name2</name><desc>Desc2</desc></step></steplist></code>

To deserialize this XML, define the following class:

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

Example usage

The following test code demonstrates the deserialization process:

<code class="language-csharp">string testData = @"<StepList>
                        <Step>
                            <Name>Name1</Name>
                            <Desc>Desc1</Desc>
                        </Step>
                        <Step>
                            <Name>Name2</Name>
                            <Desc>Desc2</Desc>
                        </Step>
                    </StepList>";

XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
    StepList result = (StepList)serializer.Deserialize(reader);
}</code>

Load from file

If the XML data is stored in a file, it can be deserialized using FileStream:

<code class="language-csharp">using (FileStream fileStream = new FileStream("<你的文件路径>", FileMode.Open))
{
    StepList result = (StepList)serializer.Deserialize(fileStream);
}</code>

By following these guidelines and using the provided examples, you can efficiently deserialize XML data and process it as objects in your application.

The above is the detailed content of How to Effectively Deserialize XML Data into C# Objects?. 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