C# 4.0 节点()与子代节点()的用法?
我读到C# 4.0 节点()与子代节点()的用法?,c#-4.0,.net-4.0,linq-to-xml,C# 4.0,.net 4.0,Linq To Xml,我读到节点()发出包括sub在内的所有节点 和子代节点()相同,但以递归方式 然而,我找不到任何情况下,我将需要递归的方式 什么时候我应该更喜欢使用子代节点()而不是节点() i、 e: IEnumerable nodes=从xmlTree.genderantnodes()中的nd开始 选择nd; foreach(节点中的XNode节点) 控制台写入线(节点); 输出: 问题: 当我可以使用Nodes()时,为什么我需要递归拆分它?Well为您提供调用它的节点的子节点,同时为您提供调用它的
节点
()发出包括sub在内的所有节点
和子代节点
()相同,但以递归方式
然而,我找不到任何情况下,我将需要递归的方式
什么时候我应该更喜欢使用子代节点
()而不是节点
()
i、 e:
IEnumerable nodes=从xmlTree.genderantnodes()中的nd开始
选择nd;
foreach(节点中的XNode节点)
控制台写入线(节点);
输出:
问题:
当我可以使用Nodes()时,为什么我需要递归拆分它?Well为您提供调用它的节点的子节点,同时为您提供调用它的节点的子节点
假设您有一个XML文档,您希望使用多个嵌套级别进行处理,并且希望查找所有级别的所有注释节点,那么您就可以这样做了
XDocument doc = XDocument.Parse(@"<!-- comment 1 -->
<root>
<!-- comment 2 -->
<foo>
<!-- comment 3 -->
<bar><!-- comment 4 --></bar>
</foo>
</root>
<!-- comment 5 -->");
foreach (XComment comment in doc.DescendantNodes().OfType<XComment>())
{
Console.WriteLine(comment.Value);
}
XDocument doc=XDocument.Parse(@)
");
foreach(类型()的doc.degenantNodes()中的XComment注释)
{
Console.WriteLine(comment.Value);
}
如果只使用节点
方法,则需要编写一个递归方法来查找所有注释节点
XDocument doc = XDocument.Parse(@"<!-- comment 1 -->
<root>
<!-- comment 2 -->
<foo>
<!-- comment 3 -->
<bar><!-- comment 4 --></bar>
</foo>
</root>
<!-- comment 5 -->");
foreach (XComment comment in doc.DescendantNodes().OfType<XComment>())
{
Console.WriteLine(comment.Value);
}