Reputation: 1391
I have the following xml:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<row>
<first-name>John</first-name>
<last-name>Miller</last-name>
<address>Birmingham</address>
</row>
<row>
<first-name>Rose</first-name>
<last-name>Miller</last-name>
<address>New York</address>
</row>
</root>
I want to modify the xml using XSLT in such a way that my output is as below:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<row>
<Name>John-Miller</Name>
<address>Birmingham</address>
</row>
<row>
<Name>Rose-Miller</Name>
<address>New York</address>
</row>
</root>
To summarize, I want to concatenate the <first-name>
and <last-name>
to generate a new node called <Name>
and keep the <address>
tag as it is(same thing should happen in each <row>
).
I am trying with the following XSLT, but not getting the desired output:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<xsl:template match="row">
<row>
<Name>
<xsl:value-of select="concat(//first-name,'-',//last-name)" />
</Name>
</row>
</xsl:template>
</xsl:stylesheet>
When I run the above XSLT against my input xml, I am only getting the <first-name>
and <last-name>
values of only first row.
Could you please provide the solution?
Upvotes: 0
Views: 82
Reputation: 167726
You need to use a relative path meaning you need to replace <xsl:value-of select="concat(//first-name,'-',//last-name)" />
with <xsl:value-of select="concat(first-name,'-',last-name)" />
. And you need to make sure to copy the address as well:
<xsl:template match="row">
<row>
<Name>
<xsl:value-of select="concat(first-name,'-',last-name)" />
</Name>
<xsl:copy-of select="address"/>
</row>
</xsl:template>
Upvotes: 2