[英]Linq to XML: Returning attributes from Children of the same name and Parents of the same name
所以,今天的noobie問題...
我有一個具有以下結構的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:attribute名稱的單個rowSet獲取行屬性。 換句話說,我試圖從僅包含在特定名稱的rowSet:Attribute下的“行”中提取屬性。
我試過使用:
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
我相信這是可行的,但是即使程序運行時我可以通過調試器的“結果視圖”獲取數據,我也不太想知道如何對其進行迭代。
好的,這樣我就可以使查詢正確運行(首先移動“)”),當我開始逐步執行代碼時,rowNames中就有值。 但是,以任何方式顯示信息我都做不到。 我正在控制台應用程序中玩這個游戲。
所以這是第一個問題。
第二個是,如果我開始通過將多個屬性添加到行元素來使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>
然后如何檢索元素中的所有屬性?
這似乎很基礎,這就是為什么我此刻感到很沮喪。
您可以很容易地單獨獲得名稱:
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");
只需調整弦樂即可獲得其他弦樂。 (例如,您可以將其放入方法中並使用參數。)
這有點猜測,但是您的意思是:
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") }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.