【问题标题】:How to record the path between two nodes in a xml tree?如何记录xml树中两个节点之间的路径?
【发布时间】:2016-04-12 08:41:42
【问题描述】:

我希望能够记录从 xml 树中的某个节点到另一个节点所需的路径。用这个图代替 XML 树:

   A
  / \
 B   C - D
/   / \
E  F   G

例如,如果我想记录从 D 到 E 的路径,路径将是上到父 C,上到父 A,下到子 B,下到子 E。所以也许实际记录的路径将是节点 D -> 节点 C -> 节点 A -> 节点 B -> 节点 E。我如何记录这样的路径?

【问题讨论】:

  • 对以下C# walking an XML Tree进行谷歌搜索
  • @MethodMan 已经查看了显示的大部分帖子。
  • 您要算法吗?代码? XML 库推荐?
  • @kjhughes 更多的是可以使用的好算法。

标签: c# xml recursion tree nodes


【解决方案1】:

基本上你想创建从每个节点到根的路径。然后比较从根开始的两条路径中的节点并找到最后一个匹配项。那是共同的祖先。有了它,您可以截断每条路径并将它们连接在一起。

public static string CreatePath(XElement from, XElement to)
{
  var fromToRoot = from.PathToRoot();
  var rootToTo = to.PathToRoot().Reverse();

  var commonAncestor = rootToTo.Zip(fromToRoot.Reverse(), Tuple.Create)
    .TakeWhile(nodes => nodes.Item1 == nodes.Item2)
    .Select(nodes => nodes.Item1)
    .LastOrDefault();

  if (commonAncestor == null) return "Not connected";

  return string.Join(
    "->",
    fromToRoot.TakeWhile(node => node != commonAncestor)
      .Concat(rootToTo.SkipWhile(node => node != commonAncestor))
      .Select(n => n.Name));
}

public static IEnumerable<XElement> PathToRoot(this XElement from)
{
  yield return from;
  var fromParent = from.Parent;
  while (fromParent != null)
  {
    yield return fromParent;
    fromParent = fromParent.Parent;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多