2015-09-25 109 views
1

我试图将XML反序列化成具有多个相同类型的元素的C#对象。为了清晰起见,我已经削减了内容。我的C#类看起来是这样的:将XML反序列化到C#对象列表中

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

然后我定义入口和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; 
} 

任何想法如何解决呢?

回答

5

我调整你的类反序列化的代码一点点的工作:

[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的层次结构,以便反序列化可以正常工作。

+0

太棒了!完美的作品,谢谢。 – CorribView