获取元素的XPath列表 [英] Get list of XPaths of elements

查看:217
本文介绍了获取元素的XPath列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有具有特定名称的元素的NodeList,我想拥有所有theese节点的XPath。

I have NodeList of elements with specific name and I would like to have XPath of all of theese nodes.

我找不到办法如何做到这一点。

I cannot find a way how to do that.

NodeList nList = doc.getElementsByTagName("definition");
 for (int i = 0; i < nList.getLength(); i++) {
 Node node = nList.item(i);
 System.out.println(node.GET_XPATH());
}

我正在寻找像GET_XPATH()这样的方法

I'm looking for a method like GET_XPATH()

有人知道怎么做吗?或者它是否可能?

Do someone know how to do that? Or is it even possible?

如果可以使用XSLT也可以使用它,但是如果有人在Java中知道这种可能性,则更喜欢。

If it is possible with XSLT can use it as well, but prefer if someone know about this possibility in Java.

原因:
我需要一组指向XML库的指针。定义元素的指针。

REASON: I need a set of pointers to XML library. Pointers to definition elements.

示例
输入:

<odML>
    <section>
        <type>experiment</type>
        <name>Experiment</name>
        <definition></definition>
        <property>
            <definition></definition>
        </property>
        <property>
            <definition></definition>
            <value>
                <definition></definition>
            </value>
        </property>
    </section>
    <definition></definition>
</odML>

输出:

/odML/section/definition

/odML/section/property[1]/definition

/odML/section/property[2]/definition

/odML/section/property[2]/value/definition

/odML/definition


推荐答案

以下样式表:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/"> 
    <xsl:for-each select="//definition">
        <xsl:for-each select="ancestor::*">
            <xsl:text>/</xsl:text>
            <xsl:value-of select="name()"/>
            <xsl:if test="(preceding-sibling::*|following-sibling::*)[name()=name(current())]">
                <xsl:text>[</xsl:text>  
                <xsl:value-of select="count(preceding-sibling::*[name()=name(current())]) + 1"/>
                <xsl:text>]</xsl:text>  
            </xsl:if>
        </xsl:for-each>
        <xsl:text>/definition</xsl:text>    
        <xsl:if test="position()!=last()">
            <xsl:text>&#10;</xsl:text>  
        </xsl:if>
    </xsl:for-each>
</xsl:template>  

</xsl:stylesheet>

当应用于您的示例输入时,将返回:

when applied to your example input, will return:

/odML/section/definition
/odML/section/property[1]/definition
/odML/section/property[2]/definition
/odML/section/property[2]/value/definition
/odML/definition

这篇关于获取元素的XPath列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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