简体   繁体   English

使用列表将 XML 反序列化为 C# 对象

[英]Deserialize XML into C# object with list

I'm trying to deserialize an XML into a C# object that has numerous elements of the same type.我正在尝试将 XML 反序列化为具有许多相同类型元素的 C# 对象。 I've pared down the contents for clarity.为清楚起见,我缩减了内容。 My C# class looks like this:我的 C# 类如下所示:

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

Then I define the Entry and RootElement classes as follows:然后我定义 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; }
}

And the structure of the XML I'm trying to deserialize looks like this:我试图反序列化的 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>

As you can see there will be multiple RootElement elements that I want to deserialize into the List of the C# object.正如您所看到的,我想将多个 RootElement 元素反序列化到 C# 对象的列表中。 To deserialize I use the following:要反序列化,我使用以下内容:

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

Any ideas how to fix it?任何想法如何解决它?

I tweaked your classes a little bit for your deserialization code to work:我稍微调整了你的类,让你的反序列化代码工作:

[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; }
}

Now it works fine.现在它工作正常。

I don't know why you declared your XmlRoot as "Form" as there is no element in the XML with that name so I replaced it with "Entry".我不知道您为什么将 XmlRoot 声明为“Form”,因为 XML 中没有具有该名称的元素,因此我将其替换为“Entry”。

You cannot use an Entry class with entryvalue1 and entryvalue2 properties because they are direct children of the root (Event) and there is no child as Entry.不能使用具有 entryvalue1 和 entryvalue2 属性的 Entry 类,因为它们是根(事件)的直接子级,并且没有子级作为 Entry。 In short your classes must reflect the hierarchy of the XML so that deserialization can work properly.简而言之,您的类必须反映 XML 的层次结构,以便反序列化可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM