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!!!
Elementonly returns the immediate child node. To recursively browse the xml tree, useDescendantsinstead.To successively enumerate the students then the teachers, you could do something like: