Home >Backend Development >C++ >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:
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>
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>
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!