XPath 1 query and attributes name

后端 未结 2 1736
广开言路
广开言路 2021-02-04 15:41

First question: is there any way to get the name of a node\'s attributes?




        
相关标签:
2条回答
  • 2021-02-04 15:43

    First question: is there any way to get the name of a node's attributes?

    <node attribute1="value1" attribute2="value2" />

    Yes: This XPath expression (when node is the context (current) node)):

        name(@*[1])

    produces the name of the first attribute (the ordering may be implementation - dependent)

    and this XPath expression (when node is the context (current) node)):

        name(@*[2])

    produces the name of the second attribute (the ordering may be implementation - dependent).

    Second question: is there a way to get attributes and values as value pairs? The situation is the following:

    <node attribute1="10" attribute2="0" />

    I want to get all attributes where value>0 and this way: "attribute1=10".

    This XPath expression (when the attribute named "attribute1" is the context (current) node)):

        concat(name(), '=', .)

    produces the string:

        attribute1=value1

    and this XPath expression (when the node node is the context (current) node)):

        @*[. > 0]

    selects all attributes of the context node, whose value is a number, greater than 0.

    In XPath 2.0 one can combine them in a single XPath expression:

        @*[number(.) > 0]/concat(name(.),'=',.)

    to get (in this particular case) this result:

        attribute1=10

    If you are using XPath 1.0, which is less powerful, you'll need to embed the XPath expression in a hosting language, such as XSLT. The following XSLT 1.0 thransformation :

    <xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="text"/>
    
      <xsl:template match="/*">
          <xsl:for-each select="@*[number(.) > 0]">
            <xsl:value-of select="concat(name(.),'=',.)"/>
          </xsl:for-each>
        </xsl:template>
    </xsl:stylesheet>
    

    when applied on this XML document:

    <node attribute1="10" attribute2="0" />
    

    Produces exactly the same result:

        attribute1=10

    0 讨论(0)
  • 2021-02-04 15:50

    It depends a little bit on the context, I believe. In most cases, I expect you'd have to query "@*", enumerate over the items, and call "name()" - but it may work in some tests.

    Re the edit - you can do:

    @*[number(.)>0]
    

    to find attributes matching your criteria, and:

    concat(name(),'=',.)
    

    to display the output. I don't think you can do both at once, though. What is the context here? xslt? what?

    0 讨论(0)
提交回复
热议问题