0

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?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.