developer
developer

Reputation: 7400

XSL & XPath - Select Element Name of Attribute

I have a rather specific question perhaps..

I have a user that will enter in some criteria on a form, and then it builds an XPath from their input. Let's say their input creates the following:

//*[@color='red']/@*

Which essentially means they want to see all attributes of any element with the @color = red.

I can display exactly what the expression asks for (all attributes), but I wanted to add information that could be useful, such as the element's name the attributes belong to.

One option would be to add to the XPath to also display the elements name: (a shorter way to create this expression without the use of | would be nice to know.. so if you have suggestions, that would be awesome!)

//*[@color='red']/@* | //*[@color='red']

Another option (that I hope is possible) is to select the element name the attribute belongs to from the template without altering the XPath expression (because I might want to use this expression in another context without the element name).

I want to have this XSLT:

<xsl:param name="built_expression" select="//*[@color='red']/@* />
<xsl:template match="/">
    <html>
        <body>
            <table>
                <tr>
                    <th>Element Name</th>
                    <th>Element Content</th>
                </tr>

                <xsl:apply-templates select="$built_expression"/>
            </table>
        </body>
    </html>
</xsl:template>

<xsl:template match="@*|node()">
    <tr>
      <td>
        <xsl:value-of select="ELEMENT name()" />
      </td>
      <td>
        <xsl:value-of select="node()" />
      </td>
    </tr>

    ... other display stuff to do with the attributes ...
</xsl:template>

This obviously doesn't work... but I hope you get my point..

<xsl:value-of select="name()"/>

just returns the name of the attribute, but I need to select the name of the attribute's element.

Thanks! Let me know if I need to clarify anything!

Upvotes: 0

Views: 4826

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243569

<xsl:value-of select="name()"/>

just returns the name of the attribute, but I need to select the name of the attribute's element.

The element to which an attribute belongs is considered its parent, therefore:

..

when issued with the context node being an attribute, selects the element to which this attribute belongs.

To find the name of this element, simply use the XPath name() function:

name(..)

when issued with the context node being an attribute evaluates to a string, which is the name of the element that holds that attribute.

Upvotes: 2

user357812
user357812

Reputation:

You need just this XPath:

name(..)

This works if the context node is your selected attribute node.

Upvotes: 1

Related Questions