Reputation: 40750
I have the following XML document:
<root someAttribute="someValue" />
Now I want to add a tag using XSLT, so that the document will look like this:
<root someAttribute="someValue">
<item>TEXT</item>
</root>
If I repeat to use the XSLT once more it should just add another item:
<root someAttribute="someValue">
<item>TEXT</item>
<item>TEXT</item>
</root>
It sound's so easy, does it not? Here is the best I got after trying a ton of things:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" >
<xsl:param name="message" />
<xsl:output method="xml" encoding="utf-8"/>
<xsl:template match="/*">
<xsl:copy>
<xsl:copy-of select="*"/>
<item>
<xsl:value-of select="$message" />
</item>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
It does /nearly/ what I have asked for, except that it "forgets" the attributes of the root element. I have found a number of other solutions here on stackoverflow and elsewhere that have in common with my solution that they loose the attributes of the root element. How can I fix that?
Upvotes: 0
Views: 3591
Reputation: 34556
You're currently transforming only child nodes, not attributes.
<xsl:template match="root">
<xsl:copy>
<xsl:copy-of select="node()|@*"/> <!-- now does attrs too -->
<item>
<xsl:value-of select="$message" />
</item>
</xsl:copy>
</xsl:template>
Upvotes: 1