传递在 xml 中多次出现的路径

Passing a path that appears multiple times in xml

我有一个 xml 看起来像这样:

<xml>
    <doc>
        <header>A1</header>
        <body>
            <subject>B1</subject>
        </body>
    </doc>
    <doc>
        <header>A2</header>
        <body>
            <subject>B2</subject>
        </body>
    </doc>
</xml>

我试图在变量中传递 header 的路径(特别是 header=A1)。但是当我尝试调用这个变量时,我得到一个 XRTreeFrag cannot be cast to org.apache.xpath.objects.XNodeSet 错误消息

这是我的 xslt:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:variable name="path">
        <xsl:value-of select="/xml/doc[header='A1']"/>
    </xsl:variable>
    <xsl:template match="/">
        <object>
            <xsl:value-of select="$path/body/subject" />
    </xsl:template>
</xsl:stylesheet>

已找到解决方案(包括路径引用可以是 header = A1 或 header = A2 的条件:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:variable name="path1" select="/xml/doc[header='A1']">
    <xsl:variable name="path2" select="/xml/doc[header='A2']">
    <xsl:variable name="condition" select="$path1" />   
    <xsl:variable name="path" select="$path1[$condition] | $path2[not($condition)]" />      

    </xsl:variable>
    <xsl:template match="/">
        <object>
            <xsl:value-of select="$path/body/subject" />
    </xsl:template>
</xsl:stylesheet>

试试这个样式表:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:variable name="path" select="/xml/doc[header='A1']" />
    
    <xsl:template match="/">
        <object>
            <xsl:value-of select="$path/body/subject" />
        </object>
    </xsl:template>
    
</xsl:stylesheet>

结果是

<object>B1</object>