[英]Is there Better way to read XML Descendants in LINQ-to-XML?
我有這樣的代碼:
string result = xml.Root.Descendants("XYZ").Descendants("ABC").Descendants("MNO").Single().Value;
1)是否有更好的方法讀取值? 某種不依賴我必須走的節點深度的通用方法?
2)刪除對“ XYZ”,“ ABC”等的硬編碼依賴性的方法是什么?
如果您不關心父節點的依賴性,則可以直接在子代調用中轉到"MNO"
。
xml.Root.Descendants("MNO")
但是,無論它們出現在XML結構中的哪里,都會產生一系列MNO
后代。
<root>
<MNO />
<ABC>
<MNO />
</ABC>
<ABC>
<XYZ>
<MNO />
</XYZ>
</ABC>
</root>
所有MNO
元素都將在序列中。
目前尚不清楚您的真正意思,但這是您的追求嗎?
public IEnumerable<XElement> PathDescendants(
this XElement element,
params XName[] names)
{
return new[] { element }.PathDescendants(names);
}
public IEnumerable<XElement> PathDescendants(
this IEnumerable<XElement> elements,
params XName[] names)
{
return names.Aggregate(elements,
(current, name) => current.Descendants(name));
}
然后,您可以致電:
string result = xml.Root.PathDescendants("XYZ", "ABC", "MNO").Single().Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.