[英]Returning multiple xml Children with same name on single node using linq c#
我有以下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();
這可能會有所幫助:
var result =來自XElement.Load中的c(“Student.xml”)。元素(“學校”)選擇c;
//對foreach執行查詢(結果是var個學生){//做某事}
源中只有一個<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
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.