从org.w3c.dom.Node获取Xpath [英] Get Xpath from the org.w3c.dom.Node

查看:173
本文介绍了从org.w3c.dom.Node获取Xpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以从org.w3c.dom.Node获取完整的xpath吗?

Can i get the full xpath from the org.w3c.dom.Node ?

说当前节点正在指向一些xml文档的中间位置。我想提取该元素的xpath。

Say currently node is pointing to some where the middle of the xml document. I would like extract the xpath for that element.

我正在寻找的输出xpath是 // parent / child1 / chiild2 / child3 /节点。父节点xpath。只需忽略正在使用表达式并指向同一个节点的xpath。

The output xpath I'm looking for is //parent/child1/chiild2/child3/node. A parent to node xpath. Just ignore the xpath's which are having expressions and points to the same node.

推荐答案

主要是获取XPath的通用方法因为没有一个通用的XPath标识文档中的特定节点。在某些模式中,节点将被属性唯一标识( id name 可能是最常见的属性。在其他方面,每个元素(即标签)的名称足以唯一标识节点。在一些(不太可能但可能)的情况下,没有一个唯一的名称或属性将您带到特定节点,因此您需要使用基数(获取第m个孩子的第n个孩子)。

There's no generic method for getting the XPath, mainly because there's no one generic XPath that identifies a particular node in the document. In some schemas, nodes will be uniquely identified by an attribute (id and name are probably the most common attributes.) In others, the name of each element (that is, the tag) is enough to uniquely identify a node. In a few (unlikely, but possible) cases, there's no one unique name or attribute that takes you to a specific node, and so you'd need to use cardinality (get the n'th child of the m'th child of...).

编辑
在大多数情况下,创建依赖模式的功能来组装XPath并不难对于给定的节点。例如,假设您有一个文档,其中每个节点都由 id 属性唯一标识,并且您没有使用命名空间。然后(我认为)以下伪Java将可以根据这些属性返回一个XPath。 ()警告:我没有测试过这个。

EDIT: In most cases, it's not hard to create a schema-dependent function to assemble an XPath for a given node. For example, suppose you have a document where every node is uniquely identified by an id attribute, and you're not using namespaces. Then (I think) the following pseudo-Java would work to return an XPath based on those attributes. (Warning: I have not tested this.)

String getXPath(Node node)
{
    Node parent = node.getParent();
    if (parent == null) {
        return "/" + node.getTagName();
    }
    return getXPath(parent) + "/" + "[@id='" + node.getAttribute("id") + "']";
}

这篇关于从org.w3c.dom.Node获取Xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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