How to get XML element based on given value

2019-08-23 05:42发布

问题:

I want to retrieve the XML element node based on the given string value. The element node can be described at any levels in a nested XML, there was no specific structure that this XML has. How to do this in XSLT transformation?

回答1:

I would use a key:

<xsl:key name="k1" match="*[not(*)]" use="."/>

then you can use e.g.

<xsl:param name="string-value" select="'foo'"/>

and

<xsl:variable name="elements" select="key('k1', $string-value)"/>

If there can be several elements with the same contents and you are only interested in the first then use

<xsl:variable name="element" select="key('k1', $string-value)[1]"/>

That assumes you want to find elements with no child elements where the string value matches your variable, other approaches like matching on the name of an element are of course also possible: <xsl:key name="k1" match="*" use="local-name()"/>.



标签: xml xslt