Deserialize XML to C# object using XmlSerializer
This article explores how to use the XmlSerializer
class to deserialize XML documents into object instances. Suppose you have an XML document with the following structure:
<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 into the corresponding class model, you need to 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>
Next, you can use XmlSerializer
to deserialize. Here is a sample test code:
<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>
To deserialize XML from a text file, load the file into FileStream
and pass it to XmlSerializer
:
<code class="language-csharp">using (FileStream fileStream = new FileStream("<文件路径>", FileMode.Open)) { StepList result = (StepList)serializer.Deserialize(fileStream); }</code>
Please replace <文件路径>
with the actual path to your XML file.
The above is the detailed content of How to Deserialize XML into C# Objects Using XmlSerializer?. For more information, please follow other related articles on the PHP Chinese website!