Cor*_*iew 1 c# xml xml-deserialization deserialization
我正在尝试将XML反序列化为具有许多相同类型元素的C#对象.为了清楚起见,我已经减少了内容.我的C#类看起来像这样:
[XmlInclude(typeof(RootElement))]
[XmlInclude(typeof(Entry))]
[Serializable, XmlRoot("Form")]
public class DeserializedClass
{
public List<Entry> listEntry;
public RootElement rootElement { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后我定义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; }
}
Run Code Online (Sandbox Code Playgroud)
我试图反序列化的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>
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我将要将多个RootElement元素反序列化到C#对象的List中.要反序列化我使用以下内容:
XmlSerializer serializer = new XmlSerializer(typeof(DeserializedClass));
using (StringReader reader = new StringReader(xml))
{
DeserializedClass deserialized = (DeserializedClass)serializer.Deserialize(reader);
return deserialized;
}
Run Code Online (Sandbox Code Playgroud)
任何想法如何解决它?
我为你的反序列化代码稍微调整了一下你的类:
[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; }
}
Run Code Online (Sandbox Code Playgroud)
现在它工作正常.
我不知道为什么你将XmlRoot声明为"Form",因为XML中没有带有该名称的元素,所以我将其替换为"Entry".
您不能将Entry类与entryvalue1和entryvalue2属性一起使用,因为它们是root(Event)的直接子级,并且没有子级作为Entry.简而言之,您的类必须反映XML的层次结构,以便反序列化可以正常工作.