更新时间:2023-01-17 18:54:07
以下是一些完整的示例代码,这些代码将捕获值:
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 };