我的xml就像这样
<?xml version="1.0" encoding="utf-8" ?><people>
<person>
<key>title</key>
<details>Kate</details>
<contact>Smith</contact>
<age>27</age>
<key>childnodes</key>
<person>
<key>All</key>
<details>Details</details>
<contact>900033</contact>
<details>Adress</details>
<contact>housenumber</contact>
</person>
</person>
<person>
<key>title</key>
<contact>Manu</contact>
<age>30</age>
<key>childnodes</key>
<person>
<key>subnode</key>
<details>Details</details>
<contact>Premraj</contact>
<details>Gandhinagar</details>
<contact>888444</contact>
</person>
</person>
<person>
<details>Ann</details>
<contact>Peterson</contact>
<age>27</age>
</person>
</people>
我想用两种方式解析xml,如果密钥包含“childnodes”('&lt; key&gt; childnodes&lt; key&gt;'),然后将数据添加到列表框或列表中,如果没有“ childnodes“将值添加到listbox1或list1。我必须检查节点密钥是否包含子节点。如果您知道解决方案,请帮助我
答案 0 :(得分:0)
首先,您的XML无效。您缺少</contact>
结束标记以及</people>
。此外,考虑到你如何处理chid条目,结构是可怕的。它应该是这样的:
<people>
<person>
<name>title</name>
<address>Kate</address>
<phone>Smith</phone>
<age>27</age>
<children>
<person>
<name>sub</name>
<address>Details</address>
<phone>900033</phone>
</person>
</children>
</person>
<person>
<name>title</name>
<phone>Manu</phone>
<age>30</age>
<children>
<person>
<name>AnotherName</name>
<address>Details</address>
<phone>900033</phone>
</person>
</children>
</person>
</people>
其次,您可以序列化您的类,然后执行适当的绑定。例如,您案例的常规序列化结构如下所示:
[XmlRoot("people")]
public class People
{
[XmlElement("person")]
public List<Person> RegisteredPeople { get; set; }
}
public class Person
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("address")]
public string Address { get; set; }
[XmlElement("phone")]
public string Phone { get; set; }
[XmlArray("children")]
[XmlArrayItem("person")]
public List<Person> Children { get; set; }
}
反序列化器应该这样:
XmlSerializer serializer = new XmlSerializer(typeof(People));
StringReader reader = new StringReader(YOUR_XML);
People p = (People)serializer.Deserialize(reader);