Simple XSLT Attribute Addition
I'm looking to do some really simply XSLT on my XML document, which has a structure like:
<XML>
<TAG1 attribute1="A">
<IRRELEVANT />
<TAG2 attribute2="B" attribute3="34" />
</TAG1>
</XML>
And am trying to make a XSLT which does the following:
- Copy everything
- If TAG2@attribute1="A" AND TAG2@attribute2="B" AND there is no TAG2@attribute4, then add @attribute4 to TAG2 and have its value to be the value of TAG2@attribute3
My unsuccessful attempt is below. The error I'm getting is "xsl:attribute: Cannot add attributes to an element if children have been already added to the element."
Thanks!
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="newDocumentHeader" />
<!-- copy idiom copying ALL nodes -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
开发者_JS百科 </xsl:copy>
</xsl:template>
<!-- override for special case -->
<xsl:template match="TAG1[@attribute1='A']/TAG2[@attribute2='B'][not(@attribute4)]">
<xsl:attribute name="attribute4">
<xsl:value-of select="@attribute3" />
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<xsl:template match="TAG1[@attribute1 = 'A']/TAG2[@attribute2= 'B' ][not(@attribute4)]">
<xsl:copy>
<xsl:attribute name="attribute4">
<xsl:value-of select="@attribute3" />
</xsl:attribute>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Result:
<XML>
<TAG1 attribute1="A">
<IRRELEVANT />
<TAG2 attribute4="34" attribute2="B" attribute3="34" />
</TAG1>
</XML>
What is missing in your XSLT code is just the copy of the matched element. However, in your case (Simple XSLT Attribute Addition) you can override directly attribute3
node:
<xsl:template match="TAG1[@attribute1='A']
/TAG2[@attribute2='B' and not(@attribute4)]
/@attribute3">
<xsl:copy-of select="."/>
<xsl:attribute name="attribute4">
<xsl:value-of select="." />
</xsl:attribute>
</xsl:template>
Integrated in your current transform, produces:
<XML>
<TAG1 attribute1="A">
<IRRELEVANT></IRRELEVANT>
<TAG2 attribute2="B" attribute3="34" attribute4="34"></TAG2>
</TAG1>
</XML>
精彩评论