Parsing xml using c# and windows phone 7

ε祈祈猫儿з 提交于 2019-12-13 21:04:24

问题


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!!!


回答1:


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);
}



回答2:


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.



来源:https://stackoverflow.com/questions/13588868/parsing-xml-using-c-sharp-and-windows-phone-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!