2011-02-03 88 views
0

我有以下XML並希望返回所有「學校」子項,但我只獲得第一個子項。 (jeffersion/08.36)我高高低低地ban着頭。我錯過了什麼?使用linq c在單個節點上返回多個具有相同名稱的xml子項#

<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

你知道你的XML文件中缺少`>`? mainline 64.36`我可以想象爲什麼你不會從一個沒有格式化的xml文件中獲得更多結果。 – Bazzz 2011-02-03 14:03:12

回答

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 
       }; 
+0

謝謝你尼克!你也碰到了頭上的釘子。我必須用XML來生活,因爲我是從API獲取的。 – mokumaxCraig 2011-02-03 14:10:26

1

這可能是有益的:

VAR的結果=從XElement.Load中的c(「Student.xml」)。元素(「學校」) select c;

//執行查詢 的foreach(VAR學生結果) {// 做一些 }

+0

我的朋友還建議我添加此聲明,它有助於結束,我不明白why.AddRange(results); – iTSrAVIE 2011-02-03 14:05:04

相關問題