I have a file.xml
<?xml version="1.0"?>
<Report>
<row>
<field1>test1</field1>
<field2>test2</field2>
<field3>test3</field3>
</row>
<row>
<field1>test4</field1>
<field2>test5</field2>
<field3>test6</field3>
</row>
</Report>
And a lookup.xml
<?xml version="1.0"?>
<lookup>
<field1>fieldA</field1>
<field2>fieldB</field2>
<field3>fieldC</field3>
</lookup>
I am trying to get following output
<?xml version="1.0"?>
<Report>
<row>
<fieldA>test1</fieldA>
<fieldB>test2</fieldB>
<fieldC>test3</fieldC>
</row>
<row>
<fieldA>test4</fieldA>
<fieldB>test5</fieldB>
<fieldC>test6</fieldC>
</row>
</Report>
So far I came up with following transform.xsl
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:strip-space elements="*"/>
<xsl:output indent="yes"/>
<xsl:variable name="lookupDoc" select="document('lookup.xml')"/>
<xsl:template match="Report">
<Items>
<xsl:apply-templates/>
</Items>
</xsl:template>
<xsl:template match="row">
<Item>
<xsl:apply-templates/>
</Item>
</xsl:template>
<xsl:template match="row/*">
<xsl:variable name="this" select="."/>
<xsl:variable name="lookup">
<xsl:for-each select="$lookupDoc">
<xsl:key name="k1" match="local-name()" use="text()"/>
<xsl:value-of select="key('k1', local-name($this))"/>
</xsl:for-each>
</xsl:variable>
<fieldName name="{$lookup}">
<xsl:value-of select="."/>
</fieldName>
</xsl:template>
</xsl:stylesheet>
New to Xsl hence mot sure why getting compiler error
It looks like you had the right idea (and a novel one at that), but there were some places that needed fixing. Please try this:
In order for
key()to locate values in the$lookupDocDOM,key()needs to be used in the context of that DOM, and that’s what the last template is for. When this is run on your sample inputs the result is your requested output:With some modification, it would have been also possible to use the
for-eachapproach you were trying to use, since that’s another way to get inside the$lookupDocDOM. The following XSLT should have the same result as the one above and is more similar to your original atttempt: