I am new user to XSLT and have been struggling with this problem.
Source XML:
<ABC X="" Y="" Z=""/>
Result XML:
<CDE F="">
<ABC X="" Y=""开发者_JAVA百科 Z"" G=""/>
</CDE>
Thus I need to
- Create a root node with an attribute with a default value in the result xml.
- Copy node ( source has one node only) from source to result xml.
- Add additional attributes to node copied from source xml.
I am able to do these separately but I am not able to do all of these in one XSLT.
Given your assumptions, seems you need one minimal template:
<xsl:template match="ABC">
<CDE F="">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="G">hello</xsl:attribute>
</xsl:copy>
</CDE>
</xsltemplate>
or, if you prefer:
<xsl:template match="/">
<CDE F="">
<xsl:apply-templates select="ABC"/>
</CDE>
</xsl:template>
<xsl:template match="ABC">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="G">hello</xsl:attribute>
</xsl:copy>
</xsl:template>
Your example XML doesn't need it (see @empo's answer), but when starting out the single most important thing to learn is the "identity transform" template. It basically copies all of your XML input as-is and unmodified. Any changes you need to make can usually be done by overriding the identity transform with other templates.
Here's an example stylesheet that gives you the output you're looking for:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<!--IDENTITY TRANSFORM-->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/ABC">
<CDE F="">
<ABC G="">
<xsl:copy-of select="@*"/>
</ABC>
</CDE>
</xsl:template>
</xsl:stylesheet>
NOTE: The "identity transform" doesn't get used when processing your input XML because the match="/ABC"
template handles the one element that you have. However, if you were to add something to your XML it would be included in the output unchanged.
For example, this modified XML input:
<ABC X="" Y="" Z="">
<FOO BAR=""/>
</ABC>
transfomed with the following stylesheet (same as above, only I added the <xsl:apply-templates/>
to the /ABC
template):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<!--IDENTITY TRANSFORM-->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/ABC">
<CDE F="">
<ABC G="">
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</ABC>
</CDE>
</xsl:template>
</xsl:stylesheet>
produces the following output:
<CDE F="">
<ABC G="" X="" Y="" Z="">
<FOO BAR=""/>
</ABC>
</CDE>
精彩评论