如何使用LINQ to XML获取特定的嵌套XML元素的值 [英] How to get the value of a specific nested XML element using LINQ to XML
问题描述
我有这样的XML
<Root>
<NodeA>
<NodeA1>
<NodeA11>
<SameNameNode>
<SameNameNodeChild1>Value 1</SameNameNodeChild1>
<SameNameNodeChild2>Value 2</SameNameNodeChild2>
</SameNameNode>
</NodeA11>
</NodeA1>
</NodeA>
<NodeB>
<SameNameNode>
<SameNameNodeChild1>Value 3</SameNameNodeChild1>
<SameNameNodeChild2>Value 4</SameNameNodeChild2>
</SameNameNode>
</NodeB>
<NodeC>
<NodeC1>
<SameNameNode>
<SameNameNodeChild1>Value 5</SameNameNodeChild1>
<SameNameNodeChild2>Value 6</SameNameNodeChild2>
</SameNameNode>
</NodeC1>
</NodeC>
</Root>
如您所见,"SameNameNode"及其子项出现在嵌套不同级别的几个位置,但名称相同.如何仅使用LINQ to XML获得值1"和值2"的元素值.谢谢.
As you can see the "SameNameNode" and its childs appear at a few places at different level of nesting but the names are the same. How do I get the element values of "Value 1" and "Value 2" only using LINQ to XML. Thank you.
推荐答案
以下是一些完整的示例代码,这些代码将捕获值:
Here is some complete sample code that will grab the values:
public static void Main()
{
var xdoc = XDocument.Parse(@"
<Root>
<NodeA>
<NodeA1>
<NodeA11>
<SameNameNode>
<SameNameNodeChild1>Value 1</SameNameNodeChild1>
<SameNameNodeChild2>Value 2</SameNameNodeChild2>
</SameNameNode>
</NodeA11>
</NodeA1>
</NodeA>
<NodeB>
<SameNameNode>
<SameNameNodeChild1>Value 3</SameNameNodeChild1>
<SameNameNodeChild2>Value 4</SameNameNodeChild2>
</SameNameNode>
</NodeB>
<NodeC>
<NodeC1>
<SameNameNode>
<SameNameNodeChild1>Value 5</SameNameNodeChild1>
<SameNameNodeChild2>Value 6</SameNameNodeChild2>
</SameNameNode>
</NodeC1>
</NodeC>
</Root>");
var results = xdoc.Root
.Elements("NodeA")
.Elements("NodeA1")
.Elements("NodeA11")
.Elements("SameNameNode")
.Descendants()
.Select(e => new { ElementName = e.Name, ElementValue = e.Value });
foreach (var result in results)
Console.WriteLine("Name = {0}, Value = {1}", result.ElementName, result.ElementValue);
}
这将输出:
Name = SameNameNodeChild1, Value = Value 1
Name = SameNameNodeChild2, Value = Value 2
您可能需要调整查询-我假设您想要"SameNameNode"的所有后代,但您可能只想过滤某些子元素.
You may need to tweak the query -- I'm assuming you want all descendants of "SameNameNode", but you may want to filter only certain sub-elements.
@Mun,要回答有关LINQ查询语法的问题,您可以使用此代码执行相同的操作.这两个代码是等效的:
@Mun, to answer your question about the LINQ query syntax, you can do the same thing with this code. The 2 pieces of code are equivalent:
var results = from nodeAElem in xdoc.Root.Elements("NodeA")
from nodeA1Elem in nodeAElem.Elements("NodeA1")
from nodeA11Elem in nodeA1Elem.Elements("NodeA11")
from sameNameNodeElem in nodeA11Elem.Elements("SameNameNode").Descendants()
select new { ElementName = sameNameNodeElem.Name, ElementValue = sameNameNodeElem.Value };
这篇关于如何使用LINQ to XML获取特定的嵌套XML元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!