【问题标题】:Deserialize XML into C# object with list使用列表将 XML 反序列化为 C# 对象
【发布时间】:2015-12-23 20:15:31
【问题描述】:

我正在尝试将 XML 反序列化为具有许多相同类型元素的 C# 对象。为了清楚起见,我已经缩减了内容。我的 C# 类如下所示:

[XmlInclude(typeof(RootElement))]
[XmlInclude(typeof(Entry))]
[Serializable, XmlRoot("Form")]
public class DeserializedClass
{
    public List<Entry> listEntry;
    public RootElement rootElement { get; set; }
}

然后我定义Entry和RootElement类如下:

public class RootElement 
{
    public string rootElementValue1 { get; set; }
    public string rootElementValue2 { get; set; }
}

public class Entry
{
    public string entryValue1 { get; set; }
    public string entryValue2 { get; set; }
}

我试图反序列化的 XML 的结构如下所示:

<Entry property="value">
  <entryValue1>Data 1</entryValue1>
  <entryValue2>Data 2</entryValue2>
  <RootElement>
    <rootElementValue1>Data 3</rootElementValue1>
    <rootElementValue2>Data 4</rootElementValue2>
  </RootElement>
  <RootElement>
    <rootElementValue1>Data 5</rootElementValue1>
    <rootElementValue2>Data 6</rootElementValue2>
  </RootElement>
</Entry>

如您所见,我希望将多个 RootElement 元素反序列化到 C# 对象的 List 中。要反序列化,我使用以下内容:

XmlSerializer serializer = new XmlSerializer(typeof(DeserializedClass));    
using (StringReader reader = new StringReader(xml))
{
    DeserializedClass deserialized = (DeserializedClass)serializer.Deserialize(reader);
    return deserialized;
}

有什么解决办法吗?

【问题讨论】:

    标签: c# xml deserialization xml-deserialization


    【解决方案1】:

    我稍微调整了你的类以使你的反序列化代码能够正常工作:

    [Serializable, XmlRoot("Entry")]
    public class DeserializedClass
    {
        public string entryValue1;
        public string entryValue2;
    
        [XmlElement("RootElement")]
        public List<RootElement> rootElement { get; set; }
    }
    
    public class RootElement
    {
        public string rootElementValue1 { get; set; }
        public string rootElementValue2 { get; set; }
    }
    

    现在它工作正常。

    我不知道您为什么将 XmlRoot 声明为“Form”,因为 XML 中没有具有该名称的元素,所以我将其替换为“Entry”。

    您不能使用具有 entryvalue1 和 entryvalue2 属性的 Entry 类,因为它们是根 (Event) 的直接子级,并且没有作为 Entry 的子级。简而言之,您的类必须反映 XML 的层次结构,以便反序列化可以正常工作。

    【讨论】:

      猜你喜欢
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      • 2018-07-17
      • 2018-10-11
      • 2013-03-24
      相关资源
      最近更新 更多