Load XML into dropdown list C#
I'm new to XML and C#. I want to load a dropdown list with specific items from an XML-file. I want to fill it with all the persons where cityname=City1 (Person1, Person2, Person3 and Person4). The problem is that all the persons displays in the dropdownbox on one single row, instead of one person on each row.
Please help me
Here is my XML:
<country>
<city>
<cityname>City1</cityname>
<citynr>111</citynr>
<person>
<name>Person1</name>
<name>Person2</name>
<name>Person3</name>
<name>Person4</name>
</person>
<major>
<firstname>Major1firstname</firstname>
<lastname>Major1lastname</lastname>
</major>
</city>
<city>
<cityname>City2</cityname>
<citynr>222</citynr>
<person>
<name>Person5</name>
<name>Person6</name>
<name>Person7</name>
<name>Person8</name>
</person>
<major>
<firstname>Major2firstname</firstname>
<lastname>Major2firstname</lastname>
</major>
</city>
</country>
My code:
XElement country = XElement.Load(Server.MapPath("myXML.xml"));
XElement city = (
from p in country.Elements("city")
where p.Element("cityname").Value == "City1"
select p
).First();
dropDownList.Items.Add(city.Element("person").Value);
From the MSDN documentation about XElement.Value:
Gets or sets the concatenated text contents of this element.
What you should do according to your XML structure:
XElement persons = city.Element("person");
foreach (XElement person in persons.Elements("name"))
{
dropDownList.Items.Add(person.Value);
}
链接地址: http://www.djcxy.com/p/51376.html
上一篇: 如何将对象列表转换为字符串列表
下一篇: 将XML加载到下拉列表中C#