How can I get a value from an xml key / value pair with xpath in my xslt?

I have an xml that I want to process using xslt. A good amount of data comes in pairs of key values ​​(see below). I am struggling with how to extract a base of values ​​from a key into a variable. I would like to be able to do something like this:

<xsl:variable name="foo" select="/root/entry[key = 'foo']/value"/>

but this does not seem to work. Here is an xml example.

<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
  <entry>
    <key>
      foo
    </key>
    <value>
      bar
    </value>
  </entry>
</root>

What will be the correct xpath for this?

+5
source share
3 answers

The following conversion shows two ways to achieve this - with and without using functions <xsl:key>and key():

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>

 <xsl:key name="kValueByKey"
   match="value" use="normalize-space(../key)"/>

 <xsl:template match="/">
   1. By key: <xsl:text/>

   <xsl:copy-of select="key('kValueByKey', 'foo')"/>

   2. Not using key:  <xsl:text/>

   <xsl:copy-of select="/*/*[normalize-space(key)='foo']/value"/>
 </xsl:template>
</xsl:stylesheet>

normalize-space(), <key>.

+5

XPath () :

<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
 <entry>
  <key>foo</key>
  <value>
   bar
  </value>
 </entry>
</root>

xpath contains, XML:

<xsl:variable name="foo" select="/root/entry[contains(key,'foo')]/value"/>
+4
<xsl:variable name="foo" select="/root/entry[key='foo']/value" />

, , XML foo. , .

+2

All Articles