gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:45 27 4
gpt4 key购买 nike

我正在尝试将 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# 对象的列表中。要反序列化,我使用以下内容:

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

有什么解决办法吗?

最佳答案

为了使反序列化代码正常工作,我稍微调整了您的类:

[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 类,因为它们是根(事件)的直接子项并且没有子项作为 Entry。简而言之,您的类必须反射(reflect) XML 的层次结构,这样反序列化才能正常工作。

关于c# - 使用列表将 XML 反序列化为 C# 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32791632/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com