执行摘要 - 您想要:
xml.Elements.Select(function(element) new XElement(element.Name,element.Attributes))
第一个答案:
XElement.Descendants
,或者这是个诡计?:P 这里有一个使用Descendants的示例
修正后的答案,感谢Tormod -- 感觉有点不对劲!:
Elements 给出直接的子代,正如你所寻找的那样。 Descendants 给出完整的层次结构 [就像你声称 Elements 所做的那样]。(我链接的示例清楚地说明了这一点。对于混淆表示歉意!
因此,最后,你要寻找的是(这次是 VB):
Dim xml = <Root>
<Parent id="1">
<Child>Thomas</Child>
</Parent>
<Parent id="2">
<Child>Tim</Child>
<Child>Jamie</Child>
</Parent>
</Root>
REM All nodes two levels down in the hierarchy
Dim level2Nodes = xml.Elements.SelectMany(function(element) element.Elements)
level2Nodes.Dump
REM All Child nodes, no matter where they are:
Dim children = xml.Descendants("Child")
每个元素都会生成3个不同原因的```元素,这在REMs中有所涵盖。
(将上述内容直接粘贴到VB语句模式下的
LINQPad中)
我现在明白可能会让你感到困惑的是-当你使用Elements并在可视化器中查看时,你仍然看到的是子元素:
Dim parents = xml.Elements
如果你只需要实际的名称,可以使用类似以下的方式:
Dim parentNames = xml.Elements.Select(function(element) element.Name)
请注意,在每种情况下,您都会获得两个结果。
如果您真的想剥离子元素,则需要使用以下代码:
Dim parentElements = xml.Elements.Select(function(element) new XElement(element.Name,element.Attributes))
你能否详细说明你真正想找的是什么?