问题描述
我有一个像这样的xml文件:
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>
如果我使用此代码:
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.
但是当我尝试:
var a = xml.Element("students");
a为空!!!
如何使用C#在xml文档中选择特定元素?
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. :)
以防万一...不能修改xml文件.
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.
谢谢大家!
推荐答案
Element
仅返回直接子节点.要递归浏览xml树,请改用Descendants
.
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);
}
这篇关于使用C#和Windows Phone 7解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!