我有以下XML并希望返回所有“学校”的孩子,但我只得到第一个。 (jeffersion / 08.36)我高高低低地抬起头来。我错过了什么?
<users>
<user>
<role>janitor</role>
<schools>
<school_name>jefferson</school_name>
<keycode>80.36</keycode>
<school_name>mainline</school_name>
<keycode>64.36</keycode>
<school_name>south side</school_name>
<keycode>31</keycode>
</schools>
</user>
</users>
这只返回第一条记录。
var results= from schools in myXmlDoc.Descendants("schools")
select new
{
SchoolName = schools.Element("school_name").Value,
KeyCode = schools.Element("keycode").Value
};
我也试过了:
var results= (from schools in myXmlDoc.Descendants("schools")
select new
{
SchoolName = schools.Element("school_name").Value,
KeyCode = schools.Element("keycode").Value
}.ToList();
这只获得了第一所学校的价值观:
var schools = (from c in xml.Descendants("user")
select new
{
Name = c.Element("role").Value,
Fields = c.Elements("schools")
.Select(f => new
{
SchoolName = f.Element("school_name").Value,
Keycode = f.Element("keycode").Value
}).ToArray()
}).ToList();
答案 0 :(得分:1)
这可能会有所帮助:
var result =来自XElement.Load中的c(“Student.xml”)。元素(“学校”) 选择c;
//执行查询 foreach(结果中的var学生) { //做一点事 }
答案 1 :(得分:1)
您的源中只有一个<schools>
元素,这就是为什么只返回一个条目。 XML的结构不是特别好 - 最好有一个包含每个school_name / keycode对的<school>
元素。但假设你必须忍受它,以下应该有效:
var results= from school in myXmlDoc.Descendants("school_name")
select new
{
SchoolName = school.Value,
KeyCode = school.ElementsAfterSelf("keycode").First().Value
};