137
<StepList>
  <Step>
    <Name>Name1</Name>
    <Desc>Desc1</Desc>
  </Step>
  <Step>
    <Name>Name2</Name>
    <Desc>Desc2</Desc>
  </Step>
</StepList>

我有这个 XML,我应该如何为类建模以便能够使用XmlSerializer对象反序列化它?

4

2 回答 2

256

你的课程应该是这样的

[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);
}
于 2012-05-09T14:56:04.490 回答
36

上面的评论是正确的。你缺少装饰器。如果你想要一个通用的反序列化器,你可以使用它。

public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
    T returnObject = default(T);
    if (string.IsNullOrEmpty(XmlFilename)) return default(T);

    try
    {
        StreamReader xmlStream = new StreamReader(XmlFilename);
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        returnObject = (T)serializer.Deserialize(xmlStream);
    }
    catch (Exception ex)
    {
        ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
    }
    return returnObject;
}

然后你会这样称呼它:

MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);
于 2016-06-03T16:13:05.700 回答