Suppose I have the following collection of "word" elements:

<word>
<id>1</id>
<text>My</text>
</word>
<word>
<id>2</id>
<text>name</text>
</word>
<word>
<id>3</id>
<text>is</text>
</word>
<word>
<id>4</id>
<text>Joe</text>
</word>

Given an integer ID value, in order to find the corresponding TEXT, I can do this:

<xsl:key name="word-by-id" match="word" use="id"/>
return key('word-by-id', string($ID))/text

But what if word are instead specified as

<word id=1>
<text>My</text>
</word>

How do I need to change the "xsl:key" in order to retrieve TEXT using ID?

Thanks

make word.xml valid

<?xml version="1.0"?>
<root>
	<word>
		<id>4</id>
		<text>Joe</text>
	</word>
	
	<word>
		<id>2</id>
		<text>name</text>
	</word>
	<word>
		<id>3</id>
		<text>is</text>
	</word>
	<word>
		<id>1</id>
		<text>My</text>
	</word>
</root>

then use xslt

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="xml" indent="yes"/>
	<xsl:key match="word" name="idkey" use="id"/>
	<xsl:template match="/">
		<root>
			<xsl:apply-templates select="root"/>
		</root>
	</xsl:template>
	<xsl:template match="root">
		<xsl:for-each select="//word[generate-id() = generate-id(key('idkey', id)[1])]">
			<xsl:sort select="id" data-type="number"/>
			<xsl:choose>
			<xsl:when test="position()=last()">
			<xsl:value-of select="text"/>
			</xsl:when>
			<xsl:otherwise>
			<xsl:value-of select="concat(text,' ')"/>
			</xsl:otherwise>
			</xsl:choose>
		</xsl:for-each>
	</xsl:template>
</xsl:stylesheet>

result

<?xml version='1.0' encoding='utf-8' ?>
<root>My name is Joe</root>

Assuming the revised document looks like this

<?xml version="1.0"?>
<root>
        <word id="4">
                <text>Joe</text>
        </word>
        <word id="2">
                <text>name</text>
        </word>
        <word id="3">
                <text>is</text>
        </word>
        <word id="1">
                <text>My</text>
        </word>
</root>

then

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:output method="text"/>

   <xsl:variable name="theID" select='1' />

   <xsl:key match="word" name="idkey" use="@id"/>

   <xsl:template match="root">
      <xsl:value-of select="key('idkey',$theID)/text"/><xsl:text>
</xsl:text>
   </xsl:template>

</xsl:stylesheet>

outputs "My"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.