1

Is it possible to change given XML structure

<Cars>
    <Car>Honda</Car>
    <Car>Ferrari</Car>
</Cars>

with XLST to

<Cars>
    <Honda></Honda>
    <Ferrari></Ferrari>
</Cars>

I know XSLT a little, but I'm not sure how to create variable tags.

Thanks everybody. I appreciate all three answers and have up voted them.

2
  • you'll need a template which at least matches the root element (when answering before I assumed this was a small example as part of a larger XSLT). I've updated my answer to include <xsl:template match="/">. Commented Aug 30, 2011 at 8:44
  • thanks for quick answer, I'm only starting to learn XLST, if it weren't for that, I would have accepted your answer. Commented Aug 30, 2011 at 8:47

3 Answers 3

3

You could use <xsl:element> to create elements by a given name. E.g. in your case it will be something like:

<xsl:template match="Car">
    <xsl:element name="{text()}"></xsl:element>
</xsl:template>

UPD: This is a fragment. Usually it is a good approach for such transformations which intended just to modify a few nodes in the tree. You define the copy-template:

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

which just copies the whole xml tree as is and then add some customised templates for particular elements, attributes, etc, e.g. as for the "Car" above.

Sign up to request clarification or add additional context in comments.

Comments

3

You're looking for xsl:element, with a name computed at run-time using curly braces like so:

<xsl:template match="/">
    <xsl:for-each select="Cars/Car">
        <xsl:element name="{.}"/>
    </xsl:for-each>
</xsl:template>

Comments

2

Try this:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:apply-templates />
    </xsl:template>

    <xsl:template match="Cars">
        <Cars>
            <xsl:for-each select="Car">
                <xsl:element name="{.}"/>
            </xsl:for-each>
        </Cars>
    </xsl:template>
</xsl:stylesheet>

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.