选择在属性中定义了 XPath 的节点 [英] Select nodes with XPath defined in attribute

查看:28
本文介绍了选择在属性中定义了 XPath 的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用在同一 XML 文档的属性中定义的 XPath 来选择节点.XML 文件示例:

I would like to select nodes using the XPath which is defined in an attribute in the same XML document. An example XML file:

<section count-node="table/row">
    <table>
        <row>row1</row>
        <row>row2</row>
        <row>row3</row>
    </table>
</section>

现在我想使用 XSLT 来获取行数,例如

Now I would like to use XSLT to get the number of rows, e.g.

<xsl:template match="section">
    <xsl:variable name="count" select="count({MY VALUE FOR @count-node}})"/>
    <xsl:value-of select="$count"/>
</xsl:template>

哪里

count({MY VALUE FOR @count-node}})

应该换成

count(/table/row)

处理样式表时.这当然应该返回

when processing the stylesheet. This should of course return

3

我无法在样式表中使用/table/row",因为我不知道元素的内容.它不一定是表格,或者表格可能是嵌套的.

I cannot use '/table/row' in the stylesheet as I do not know the content of the element. It does not have to be a table, or the table maybe nested.

我该怎么做?

推荐答案

如果您的 XPath 表达式相当简单,那么以下可能有效:

If your XPath expressions are rather simple, then the following might work:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="section">
        <xsl:variable name="expression" select="@count-node" as="node()"/>   
        <xsl:value-of select="count( 
            descendant::*[$expression = 
                          string-join(
                            (ancestor::*[.=$expression/../descendant::*]/name(), 
                             name()),
                            '/')] )"/>
     </xsl:template>
</xsl:stylesheet>

它计算计算出的 XPath(相对于 section)等于来自 @count-node 的 XPath 的所有后代元素.

It counts all of the descendant elements who's computed XPath (relative from the section) is equal to the XPath from the @count-node.

这篇关于选择在属性中定义了 XPath 的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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