Is it possible to change given XML structure
<Cars>
<Car>Honda</Car>
<Car>Fer开发者_StackOverflow中文版rari</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.
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.
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>
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>
精彩评论