如何获取xml文件中每个节点的完整路径? [英] How can I get full path of each node in xml file?

查看:130
本文介绍了如何获取xml文件中每个节点的完整路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用xpath来遍历xml文件.我想知道是否有一种简单的方法可以获取文件中每个节点的路径.我能想到的一种方法是将所有节点收集到一个数组中.然后将其传递给一个函数,该函数将每个节点作为参数并不断寻找父节点,直到到达文档根.所以,

I am using xpath for traversal of xml file.I want to know if there is an easy way to get path of each node in the file.One approach that I can think of is to collect all the nodes in an array.Then pass it to a function which takes each node as the argument and keeps on finding parents until document root is reached.So,

            function getPathForNode(eachXmlNode, path) {
                if ( eachXmlNode == rootNode ) {
                    return path;
                } else {
                    getPathForNode(eachXmlNode->parent, path+path_of_parent);
                }
            }

请告诉我是否有其他更好的方法或者递归函数是否正确?

Please let me know if there is any other better approach or if the recursive function is correct or not?

推荐答案

这取决于您使用的主机和 XPath 语言版本.

It depends on the host and XPath language version you use.

最简单的方法是使用具有 path 功能的 XPath 3:

The easiest way is to use XPath 3 which has the path function:

//node()/path()

或者,如果您不想在路径中使用命名空间,例如:

Or, if you do not want namespaces in the path, something like:

//node()/replace(path(), "Q[{][^}]*[}]", "")

使用 ancestor-or-self::*string-join 的 XPath 2 解决方案:

XPath 2 solution using ancestor-or-self::* and string-join:

for $node in //node()
return concat( "/",
  string-join(
    for $a in $node/ancestor-or-self::*, 
        $name in node-name($a)
    return concat($name, "[",  $a/../node()[node-name(.) = $name]/(if (. is $a) then position() else ()), "]")
  , "/"),
  if ($node/self::text()) then concat("/text()[",$node/../text()/(if (. is $node) then position() else ()),"]") else ()
)

这篇关于如何获取xml文件中每个节点的完整路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆