我想在我的 XML 文档上做一些非常简单的 XSLT,它的结构如下:
<XML>
<TAG1 attribute1="A">
<IRRELEVANT />
<TAG2 attribute2="B" attribute3="34" />
</TAG1>
</XML>
我正在尝试制作一个执行以下操作的 XSLT:
- 复制所有内容
- 如果 TAG2@attribute1="A"AND TAG2@attribute2="B"并且没有 TAG2@attribute4,则将 @attribute4 添加到 TAG2 并使其值为 TAG2@attribute3 的值
我不成功的尝试如下。我得到的错误是 “xsl:attribute:如果已将子项添加到元素,则无法向该元素添加属性。”
谢谢!
<?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() | @*" />
</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>
结果:
<XML>
<TAG1 attribute1="A">
<IRRELEVANT />
<TAG2 attribute4="34" attribute2="B" attribute3="34" />
</TAG1>
</XML>
关于xml - 简单的 XSLT 属性添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6815512/