【问题标题】:C# How to traverse a subtree with recursion?C#如何使用递归遍历子树?
【发布时间】:2015-07-14 11:13:09
【问题描述】:

我想,我必须首先设置我想要探索子树的起点,然后构建一个递归调用。

例子:

<realRoot>
  <node>
    <desiredRoot>
      <rootChild/>
        <nestedChild/>
      <rootChild/>
    </desiredRoot>
  </node>
 </realRoot>

我的目标是只进行迭代:

<desiredRoot>
      <rootChild/>
        <nestedChild/>
      <rootChild/>
</desiredRoot>

C# 中最好的解决方案是什么?

【问题讨论】:

标签: c# xml recursion linq-to-xml


【解决方案1】:

如果我理解正确:一个简单的例子显示元素的名称和类型:

            var xmlstr = @"<realRoot>
  <node>
    <desiredRoot>
      <rootChild/>
      <nestedChild/>
      <rootChild/>
    </desiredRoot>
  </node>
 </realRoot>";
            var xd = XDocument.Parse(xmlstr);
            var el = xd.Root.Element("node").Descendants();
            foreach (var x in el)
                Console.WriteLine("{0} [{1}]", x.Name, x.NodeType);

打印:

desiredRoot [Element]
rootChild [Element]
nestedChild [Element]
rootChild [Element]

链接:https://dotnetfiddle.net/BIE0zI

【讨论】:

    猜你喜欢
    • 2018-07-12
    • 2014-03-11
    • 1970-01-01
    • 2016-09-19
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    相关资源
    最近更新 更多