2015-09-09 65 views
-3

我有以下XML:地圖XML子元素的C#類

 xml += "<?xml version=\"1.0\" encoding=\"UTF - 8\"?>"; 
     xml += "<root>"; 
     xml += " <success>true</success>"; 
     xml += " <data>"; 
     xml += " <item>"; 
     xml += "  <StateId>0</StateId>"; 
     xml += "  <StateName>Test</StateName>"; 
     xml += "  <GroupId>0</GroupId>"; 
     xml += " </item>"; 
     xml += " </data>"; 
     xml += "</root>"; 

基本上我感興趣的是根 - >數據 - >項目唯一的元素,我試圖得到它:

public static T ConvertXmlToClass<T>(string xml) 
{ 
    XmlRootAttribute xRoot = new XmlRootAttribute(); 
    xRoot.ElementName = "root"; 
    xRoot.IsNullable = true; 
    var serializer = new XmlSerializer(typeof(T), xRoot); 
    return (T)serializer.Deserialize(new StringReader(xml)); 
} 

我得到空對象,因爲實際數據在root-> data-> item中。

我試圖改變xRoot.ElementName = "root";xRoot.ElementName = "root/data";xRoot.ElementName = "root/data/item";但我有:

的InnerException信息:System.InvalidOperationException 的HResult = -2146233079 消息=沒有料到。 源= Microsoft.GeneratedCode

對象類是:

public partial class DocumentStatus 
{ 
    public DocumentStatus() 
    { 
     this.Documents = new HashSet<Document>(); 
     this.DocumentsTrackings = new HashSet<DocumentsTracking>(); 
     this.DocumentsTrackingChildDocuments = new HashSet<DocumentsTrackingChildDocument>(); 
    } 
    [XmlElement("StateId")] 
    public int StateId { get; set; } 
    [XmlElement("StateName")] 
    public string StateName { get; set; } 
    [XmlElement("GroupId")] 
    public Nullable<int> GroupId { get; set; } 

    public virtual HashSet<Document> Documents { get; set; } 
    public virtual HashSet<DocumentsTracking> DocumentsTrackings { get; set; } 
    public virtual HashSet<DocumentsTrackingChildDocument> DocumentsTrackingChildDocuments { get; set; } 
}  
+0

什麼不清楚'「數據'第1行的開始標記位置73與'root'的結束標記不匹配。 1號線,位置167 – Eser

回答

2

您應該解決您的類,以便您的序列將是有效的:

[Serializable()] 
[System.Xml.Serialization.XmlRoot("root")] 
public class SomeClass 
{ 
    public Data() 
    { 
     DataArray = new List<Data>(); 
    } 

    [XmlElement("data", typeof(Data))] 
    public List<Data> DataArray { get; set; } 
} 

[Serializable()] 
public class Data 
{ 
    public Data() 
    { 
     DocumentStatusArray = new List<DocumentStatus>(); 
    } 

    [XmlElement("item", typeof(DocumentStatus))] 
    public List<DocumentStatus> DocumentStatusArray { get; set; } 
} 

[Serializable()] 
public class DocumentStatus 
{ 
    [System.Xml.Serialization.XmlAttribute("StateId")] 
    public int StateId {get; set;} 

    [System.Xml.Serialization.XmlAttribute("StateName")] 
    public string StateName { get; set; } 

    [System.Xml.Serialization.XmlAttribute("GroupId")] 
    public GroupId groupId { get; set; } 
}