【问题标题】:How to deserialize the following file using C# XML Serialization where the root itself is the IEnumerable?如何使用根本身是 IEnumerable 的 C# XML 序列化反序列化以下文件?
【发布时间】:2013-02-01 05:51:23
【问题描述】:
<results>
    <result>
        <egov_ref_no>20121203001</egov_ref_no>
        <status>OK</status>
        <err_code>01</err_code>
    </result>
    <result>
        <egov_ref_no>20121203002</egov_ref_no>
        <status>OK</status>
        <err_code>02</err_code>
    </result>
    <result>
        <egov_ref_no>20121203003</egov_ref_no>
        <status>OK</status>
        <err_code>03</err_code>
    </result>
</results> 

上面的代码显示根节点已经是一个 IEnumerable,而在在线示例中它们只是元素。

【问题讨论】:

  • 你能发个代码吗?你如何尝试反序列化它?
  • 你有result 对象还是只想要匿名类型
  • 是的,我有一个“结果”对象,但我需要的是“结果”对象的列表。谢谢。
  • this 你的问题吗?如果是,您找到解决方案了吗?

标签: c# .net xml xml-serialization


【解决方案1】:

如果你有一个结果对象,你可以将XmlRootAttribute 传递给XmlSerializer 构造函数。在这种情况下,它的“结果”

例子:

List<Result> results = new List<Result>();

XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Result>), new XmlRootAttribute("results"));

using (FileStream stream = new FileStream(@"C:\Test.xml", FileMode.Open))
{
    results = (List<Result>)xmlSerializer.Deserialize(stream);
}

我的结果对象:

[XmlType(TypeName = "result")]
public class Result
{
    [XmlElement(ElementName = "egov_ref_no")]
    public long EgovRefNo { get; set; }

    [XmlElement(ElementName = "status")]
    public string Status { get; set; }

    [XmlElement(ElementName = "err_code")]
    public int ErrorCode { get; set; }
}

这将返回为List&lt;Result&gt;

【讨论】:

  • 非常感谢 sa_ddam 和 Andrey Gordeev。我的问题解决了。
  • 没问题,快乐编码:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-28
相关资源
最近更新 更多