这个问题已经在这里有了答案 :
将XML字符串转换为对象 (14个答案)
3年前关闭。
<StepList> <Step> <Name>Name1</Name> <Desc>Desc1</Desc> </Step> <Step> <Name>Name2</Name> <Desc>Desc2</Desc> </Step> </StepList>
我有这个XML,我应该如何对类建模,以便能够使用XmlSerializer对象反序列化它?
XmlSerializer
您的课程应如下所示
[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; } }
这是我的测试代码。
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); }
如果要读取文本文件,则应将文件加载到FileStream中并反序列化。
using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open)) { StepList result = (StepList) serializer.Deserialize(fileStream); }