您能否更简单地在另一个标签(“数据”)中反序列化 XML(“项目”)而不在“项目”获取属性中使用另一个反序列化。也许是“public Item[] Items”上的某种属性。
XML:
<body>
<request></request>
<data><![CDATA[
<items>
<item>
<property1>Name1</property1>
<property2>111</property2>
</item>
<item>
<property1>Name2</property1>
<property2>222</property2>
</item>
<item>
<property1>Name3</property1>
<property2>333</property2>
</item>
</items>]]>
</data>
</body>
测试类:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
const string xml = "<body>" +
"<request></request>" +
"<data><![CDATA[" +
"<items>" +
"<item>" +
"<property1>Name1</property1>" +
"<property2>111</property2>" +
"</item>" +
"<item>" +
"<property1>Name2</property1>" +
"<property2>222</property2>" +
"</item>" +
"<item>" +
"<property1>Name3</property1>" +
"<property2>333</property2>" +
"</item>" +
"</items>" +
"]]></data>" +
"</body>";
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
var serializer = new XmlSerializer(typeof (Body));
var response = serializer.Deserialize(new XmlNodeReader(xmlDoc)) as Body;
Assert.IsNotNull(response);
Assert.AreEqual(3, response.Items.Length);
}
}
[Serializable, XmlRoot("body")]
public class Body
{
[XmlElement("request")]
public string Request;
[XmlElement("data")]
public string Data;
public Item[] Items
{
get
{
var document = new XmlDocument();
document.LoadXml(Data);
var serializer = new XmlSerializer(typeof(ItemList));
var response = serializer.Deserialize(new XmlNodeReader(document)) as ItemList;
return response.Items;
}
}
}
[Serializable, XmlRoot("items")]
public class ItemList
{
[XmlElement("item")]
public Item[] Items;
}
[Serializable]
public class Item
{
[XmlElement("property1")]
public string Property1;
[XmlElement("property2")]
public string Property2;
}