0

我試圖將我的xml反序列化爲自定義對象,而且我很接近,但是最嵌套的元素沒有填充,而所有的父類都正常工作。c#使用嵌套類反序列化自定義類

下面是反序列化過程中的XML和類:

<?xml version="1.0" encoding="utf-8" ?> 
<dataMapping> 
    <documentType attr1="blah" attr2="blah2" attr3="blah3"> 
    <indexFields> 
     <indexField name1="field1A" name2="field1B" type="int" /> 
     <indexField name1="field2A" name2="field2B" type="int" /> 
     <indexField name1="field3A" name2="field3B" type="int" /> 
    </indexFields> 
    </documentType> 
    <documentType attr1="asdf" attr2="asdf2" attr3="asdf3"> 
    <indexFields> 
     <indexField name1="field1A" name2="field1B" type="int" /> 
     <indexField name1="field2A" name2="field2B" type="int" /> 
     <indexField name1="field3A" name2="field3B" type="int" /> 
    </indexFields> 
    </documentType> 
</dataMapping> 


[XmlRoot("dataMapping")] 
public class dataMapping 
{ 
    [XmlElement("documentType")] 
    public List<DocumentType> DocumentTypes{ get; set; } 

    public dataMapping() { } 
} 

[XmlRoot("documentType")] 
public class DocumentType 
{ 
    [XmlAttribute("attr1")] 
    public string Area { get; set; } 

    [XmlAttribute("attr2")] 
    public string Cabinet { get; set; } 

    [XmlAttribute("attr3")] 
    public string SearchGroup { get; set; } 

    [XmlElement("indexFields")] 
    public List<IndexField> IndexFields{ get; set; } 

    public DocumentType() { } 
} 

[XmlRoot("indexField")] 
public class IndexField 
{ 
    [XmlAttribute("name1")] 
    public string Name1 { get; set; } 

    [XmlAttribute("name2")] 
    public string Name2 { get; set; } 

    [XmlAttribute("type")] 
    public string DataType { get; set; } 

    public string ObjectValue { get; set; } 

    public IndexField() { } 
} 

所以,通過創建反序列化我的自定義對象時,一切都只是索引字段填入及其相關屬性。我在哪裏設置這個課程是錯誤的?

回答

0

得到它弄清楚。我需要一個類(基於我有xml結構的方式)稱爲「IndexFields」,然後包含「IndexField」列表....只是缺少一個級別。

[XmlRoot("indexFields")] 
public class IndexFields 
{ 
    [XmlElement("indexField")] 
    public List<IndexField> NestedIndexFields { get; set; } 

    public IndexFields() { } 
} 
1

嘗試添加XmlArrayItem它應該幫助

[XmlArrayItem(typeof(IndexField))] 
public List<IndexField> IndexFields{ get; set; }