【发布时间】:2015-09-09 07:07:35
【问题描述】:
我有以下 XML:
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>";
基本上我只对 root->data->item 元素感兴趣,我正在尝试获取它:
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 H结果=-2146233079 Message= 不是预期的。 Source=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; }
}
【问题讨论】:
-
不清楚的地方
The 'data' start tag on line 1 position 73 does not match the end tag of 'root'. Line 1, position 167.
标签: c# .net xml xml-serialization xmlserializer