Reputation: 1138
I have an xml file like this:
<xml>
<students>
<person name=jhon/>
<person name=jack/>
...
</students>
<teachers>
<person name="jane" />
<person name="jane" />
...
</teachers>
</xml>
If I use this code:
var xml = XDocument.Parse(myxmlstring, LoadOptions.None);
foreach(XElement studentelement in xml.Descendants("person"))
{
MessageBox.Show(studentelement.Attribute("name").Value);
}
Everything works fine! However, I don't know if I'm iteratng over the students or the teachers.
But when I try:
var a = xml.Element("students");
a is null!!!
How can I select a specific element in my xml document with c#?
It would be awesome if I could iterate over the students only first, fill some listboxes and the iterate over the teachers and do other stuff. :)
The xml file can`t be modified, just in case...
Finally, all I actually want with all of this is to get all the children of a specific element in my file.
Thanks everyone!!!
Upvotes: 0
Views: 1153
Reputation: 1500225
But when I try: var a = xml.Element("students");
a is null!!!
Yes, because xml
is the document, and there's only one directly element below it - called xml
. If you use:
var students = xml.Root.Element("students");
instead, it would look for <students>
directly beneath the root element instead, and it would work.
Or alternatively, you can use Element
twice:
var students = xml.Element("xml").Element("students");
Or use Descendants
, of course.
Additionally, you can get to an element's parent element with the Parent
property... so if you wanted to iterate over all person
elements and use the parent element name for some reason, you could certainly do that.
Upvotes: 4
Reputation: 39007
Element
only returns the immediate child node. To recursively browse the xml tree, use Descendants
instead.
To successively enumerate the students then the teachers, you could do something like:
var xml = XDocument.Parse(myxmlstring, LoadOptions.None);
var students = xml.Descendants("students");
var teachers = xml.Descendants("teachers");
foreach (var studentElement in students.Descendants("person"))
{
MessageBox.Show(studentElement.Attribute("name").Value);
}
foreach (var teacherElement in teachers.Descendants("person"))
{
MessageBox.Show(teacherElement.Attribute("name").Value);
}
Upvotes: 1