2010-11-20 32 views
1

所以,一天的noobie問題...的LINQ to XML:返回的同名從同一個名字的兒童屬性和家長

我有以下結構的XML文件:

<result> 
    <rowSet name="name"> 
    <row name="name1" /> 
    <row name="name2" /> 
    <row name="name3" /> 
    </rowSet> 
    <rowSet name="type"> 
    <row type="type1" /> 
    <row type="type2" /> 
    <row type="type3" /> 
    </rowSet> 

etc.. 

</result> 

我一直在嘗試,而不是成功,從基於rowSet:屬性名稱的單個rowSet中獲取行屬性。換句話說,我試圖從只包含在rowSet:特定名稱的屬性下的「行」中提取屬性。

我已經嘗試使用:

var rowSet = from rs in xmlDoc.Descendants("result") 
       where rs.Descendants("rowset").Attributes("name").Any(a => a.Value == "name") 
       select new 
       { 
        row = from r in xmlDoc.Descendants("row") 
          select new 
          { 
           skillID = r.Attribute("name"), 
          } 
       }; 

然而,這並沒有給多單的結果了。相當令人沮喪,並再次嘗試15種不同的建議後,我一直無法記住讀者的原始代碼。

的回答給定:

var rowNames = (from i in xmlDoc.Descendants("rowSet") 
       where (string)i.Attribute("name") == "name" 
       select i.Descendants("row")) // Had to move this last) to... 
       .Select(r => (string)r.Attribute("name")); // Here in order to get it to work 

我相信這工作,但我太noobish找出如何遍歷它,即使我可以通過的「結果視圖」獲取數據程序運行時的調試器。


好了,我能得到那個查詢正確運行(通過移動「)」先),當我開始逐步執​​行代碼時,rowNames中有值。但是,我一直很難以任何方式顯示信息。我正在玩一個控制檯應用程序,fyi。

所以這是第一個問題。

第二個是,如果我開始做我的XML比較複雜一點,通過添加多個屬性行元素,如:

<result> 
    <rowSet name="name"> 
     <row fName="Ted" lName = "Happy" /> 
     <row name="Billy" lName = "Maddison"/> 
     <row name="John" lName = "Doe"/> 
    </rowSet> 
    <rowSet name="type"> 
     <row type="type1" type2 ="Hero"/> 
     <row type="type2" type2 ="Villain" /> 
     <row type="type3" type2 ="Neutral"/> 
    </rowSet> 
</result> 

那麼如何重新獲取一個元素的所有屬性?

這似乎很基本,這就是爲什麼我現在感覺相當遲鈍。

+0

您能澄清所需的輸出嗎? – 2010-11-20 03:42:49

+0

只是想返回不同「行」的屬性。 – Josh 2010-11-20 05:00:47

回答

0

你可以很容易地單獨得到足夠的名字:

var rowNames = from i in xmlDoc.Descendants("rowSet") 
       where (string)i.Attribute("name") == "name" 
       from r in i.Descendants("row") 
       select (string)r.Attribute("name"); 

只要調整琴絃得到其他。 (例如,您可能會在方法中使用此參數並使用參數。)

+0

請參閱OP,謝謝您的輸入。 – Josh 2010-11-21 08:39:13

+0

移動paren將導致查詢行爲非常不同。請嘗試我的答案,並像這樣遍歷它:'foreach(rowNames中的字符串str)Console.WriteLine(str);' - 您應該從第一個rowSet中看到所需的所有屬性。 – cdhowie 2010-11-21 20:32:17

+0

我收到一個錯誤: 錯誤'System.Collections.Generic.IEnumerable '不包含'Attribute'的定義,也沒有接受第一個參數的擴展方法'Attribute'類型'System.Collections.Generic。IEnumerable ' – Josh 2010-11-21 21:21:15

-1

這是一些猜測,但你的意思是:

from rs in xmlDoc.Descendants("result").Descendants("rowSet") 
where (string)rs.Attribute("name") == "name" 
from r in rs.Descendants("row") 
select new { skillID = (string)r.Attribute("type") }