如何在单个 XPath 函数中连接每个元素的两个属性?

D.R*_*.R. 3 xml xpath xpath-2.0

我有以下 XML:

<xml>
    <entry key="e1" value="foo"/>
    <entry key="e2" value="bar"/>
    ...
</xml>
Run Code Online (Sandbox Code Playgroud)

我想从 XPath 获得以下输出:

e1: foo, e2: bar, ...
Run Code Online (Sandbox Code Playgroud)

我尝试使用,string-join但没有用。任何想法哪个版本的 XPath 可以做到这一点?甚至有可能吗?

(注意:我更喜欢 XPath 1.0 查询,但是,我认为这是不可能的)

Abe*_*bel 5

我尝试使用字符串连接,但没有用。关于 XPath 可以做到这一点的任何想法?甚至有可能吗?
[...] 我认为这是不可能的)

为什么不可能呢?...

无论如何,正如评论中所暗示的那样,只需使用

concat(
    entry[1]@key, ': ', 
    entry[1]@value, ', ', 
    entry[2]@key, ': ', 
    entry[2]@value) 
Run Code Online (Sandbox Code Playgroud)

其他方法:

  • XPath 2.0: string-join( (expr1, expr2, ...), '')
  • XSLT 2.0: <xsl:value-of select="expr1, expr2, ..." separator="" />
  • XPath 3.0:expr1 || expr2 || ...使用字符串连接运算符
  • 任何 XSLT 版本,为了防止重复,使用模板匹配:

    <xsl:template match="xml/entry">
        <xsl:value-of select="@key" />
        <xsl:text>: </xsl:text>
        <xsl:value-of select="@value" />
        <xsl:if test="position() != last()">,</xsl:if>
    </xsl:template>
    
    Run Code Online (Sandbox Code Playgroud)
  • 或者更通用,在属性节点上应用模板并按如下方式匹配:

    <xsl:template match="@key | @value">
        <xsl:value-of select="." />
        <xsl:text>: </xsl:text>
    </xsl:template>
    
    <xsl:template match="@value">
        <xsl:value-of select="@value" />
        <xsl:text>, </xsl:text>
    </xsl:template>
    
    Run Code Online (Sandbox Code Playgroud)
  • XSLT 3.0,使用文本值模板(TVT)编写模板:

    <xsl:template match="xml/entry" expand-text="yes">{
        @key}: {
        @value,
        if(position() != last()) then ',' else ()
    }</xsl:template>
    
    Run Code Online (Sandbox Code Playgroud)
  • XPath 2.0,更通用的方法:

    string-join(
        for $i in xml/item 
        return concat($i/@key, ': ', $i/@value),
        ', ')
    
    Run Code Online (Sandbox Code Playgroud)

    或更短:

    string-join(xml/item/concat($i/@key, ': ', $i/@value, ', ')
    
    Run Code Online (Sandbox Code Playgroud)
  • ... 或使用高阶函数( pdf ) 在 XPath 3.0 中更有趣和更容易 (?) 阅读:

    let $combine = concat(?, ': ', ?)
    return string-join(
        for $i in xml/item 
        return $combine($i/@key, $i/@value),
        ', ')
    
    Run Code Online (Sandbox Code Playgroud)

    甚至:

    string-join(
        for-each-pair(
            xml/item/@key,       (: combine this :)
            xml/item/@value,     (: with this :)
            concat(?, ': ', ?)), (: using this, in order :)
        ', ')                    (: then join :)
    
    Run Code Online (Sandbox Code Playgroud)

注意:如果您不使用 XSLT,只需忽略模板方法,您可以坚持使用提到的功能。