xpath:计算前面的元素

时间:2013-02-18 13:41:05

标签: xpath

我有一个xml结构,如下所示:

<document>
    <body>
        <section>
            <title>something</title>
            <subtitle>Something again</subtitle>
            <section>
                <p xml:id="1234">Some text</p>
                <figure id="2121"></figure>
                <section>
                    <p xml:id="somethingagain">Some text</p>
                    <figure id="939393"></figure>
                    <p xml:id="countelement"></p>
                </section>
            </section>
        </section>
        <section>
            <title>something2</title>
            <subtitle>Something again2</subtitle>
            <section>
                <p xml:id="12345678">Some text2</p>
                <figure id="939394"></figure>
                <p xml:id="countelement2"></p>
            </section>
        </section>
    </body>
</document>

如何使用XPath计算<p xml:id="countelement"></p>元素之前的数字elemtens?

修改 我只想计算父节中的数字元素,在下一节中它应该从0开始。

2 个答案:

答案 0 :(得分:1)

鉴于您使用的是 XPath 2.0兼容引擎,请找到count元素并使用所有前面的figure-element作为输入为每个引用fn:count()

这将返回同一级别上每个“countelement”之前的数字(我猜这是你真正想要的):

//p[@xml:id="countelement"]/count(preceding-sibling::figure)

这将返回每个“countelement”之前的数字和上面的数字:

//p[@xml:id="countelement"]/count(preceding-sibling::figure | parent::*/preceding-sibling::figure)

这将返回每个“countelement”之前的所有前面数字的数字和上面的级别:

//p[@xml:id="countelement"]/count(preceding::figure)

如果您受 XPath 1.0 的约束,您将无法获得多个结果。如果@id确实是一个id(因此是唯一的),您将能够使用此查询:

count(//p[@xml:id="countelement"]/preceding::figure)

如果有“反补贴”不是<p/>元素,请将p替换为*

答案 1 :(得分:0)

count(id("countelement")/preceding-sibling::figure)

请注意,两个不同元素的xml:id属性不能相同,例如“countelement”。如果希望两个不同的元素具有相同名称的属性具有相同的值“countelement”,则它必须是某些其他属性,可能是“kind”,而不是DTD属性类型ID。在这种情况下,您将使用id("countelement")来代替*[@kind="countelement"]

相关问题