Name query and attribute XPath 1

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

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

Second question: is there a way to get attributes and values ​​as pairs of values? The situation is as follows:

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

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

+6
xpath attributes
source share
3 answers

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

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

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

name(@*[1])

creates the name of the first attribute (the order may be implementation dependent)

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

name(@*[2])

creates the name of the second attribute (the order may be implementation dependent).

Second question: is there a way to get attributes and values ​​as pairs of values? The situation is as follows:

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

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

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

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

creates a line:

attribute1=value1

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

@*[. > 0]

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

In XPath 2.0, you 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 efficient, you will need to embed the XPath expression in a hosting language such as XSLT . The following XSLT 1.0 formation:

 <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 to this XML document :

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

It produces exactly the same result :

attribute1=10

+10
source share

//node/attribute::*

Tried this using the XPath Evaluator web appraiser here .

Use the XML you want to have with the node sample you provided.
Place the XPath expression on the page and click "Eval".

Hope this helps.

+3
source share

It depends a little on the context. In most cases, I expect you to have to request " @* ", list the elements and call " name() ", but it may work in some tests.

Repeat editing - you can do:

 @*[number(.)>0] 

To find attributes that match your criteria, and:

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

to display the output. Although I do not think you can do this at the same time. What is the context here? XSLT? what?

0
source share

All Articles