0

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);
2
  • 1
    try as this one : stackoverflow.com/questions/5959257/… Commented Oct 30, 2013 at 22:22
  • Actually you are adding one item : dropDownList.Items.Add(city.Element("person").Value); Commented Oct 30, 2013 at 22:22

1 Answer 1

0

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, but I don't understand. What is the name persons in the second line?
Do you mean the variable named persons, or do you mean the string argument "name"?
I mean the persons as in persons.Elements("name")
@user2939293: Note the first line in my code snippet. There is the "birthplace" of the variable persons ;)
Yes, I realized that. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.