I have two XML files. One is the main XML file and the other one is used as a lookup table. Here is the main XML:
<Report>
<row>
<field1>test1</field1>
<field2>test2</field2>
<field3>test3</field3>
</row>
<row>
<field1>test4</field1>
<field2>test5</field2>
<field3>test6</field3>
</row>
</Report>
The lookup xml file looks like this:
<lookup>
<fieldmapping name="field1">fieldA</fieldmapping>
<fieldmapping name="field2">fieldB</fieldmapping>
<fieldmapping name="field3">fieldC</fieldmapping>
</lookup>
Here is the output xml I want:
<Items>
<Item>
<FieldName name="fieldA">test1</FieldName>
<FieldName name="fieldB">test2</FieldName>
<FieldName name="fieldC">test3</FieldName>
</Item>
<Item>
<FieldName name="fieldA">test4</FieldName>
<FieldName name="fieldB">test5</FieldName>
<FieldName name="fieldC">test6</FieldName>
</Item>
</Items>
I am using the following XSLT and can not figure out how to select the value from field1, field2, and field3:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="mappingLookupDoc" select="document('lookup.xml')/lookup/fieldmapping "/>
<xsl:key name="mappingKey" match="fieldmapping " use="@name"/>
<xsl:template match="report">
<xsl:apply-templates select="$mappingLookupDoc"/>
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="/">
<Items xmlns="http://www.w3.org/1999/xhtml" schemaVersion="1.0">
<xsl:for-each select="report/row">
<Item>
<xsl:for-each select="$mappingLookupDoc">
<xsl:variable name="fieldname" select="@name"/>
<FieldName>
<xsl:attribute name="name">
<xsl:value-of select="." />
</xsl:attribute>
<xsl:value-of select="/report/row/?????"/>
</FieldName>
</xsl:for-each>
</Item>
</xsl:for-each>
</Items>
</xsl:template>
This is the way I would do it (although I like Martin's use of
xsl:key
):I modified main.xml and lookup.xml to show the dynamic name lookup.
main.xml
lookup.xml
XSLT 1.0 stylesheet
output
I would do it like this (assuming XSLT 2.0):
[edit] Here is an XSLT 1.0 rewrite of the above XSLT 2.0 stylesheet:
Maybe something like this would be simpler: