这应该相当容易,但我是XSLT的新手,我很难找到解决方案。我得到了以下XML:
<catalog>
<book id="1">
<author>Mike</author>
<title>Tomas</title>
</book>
</catalog>
我正在尝试在其上添加另一个book
条目,并将其id
从1
更改为2
。我尝试了以下但无法更改属性值。
<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="@id">
<xsl:attribute name="id">2</xsl:attribute>
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="book">
<xsl:element name="book">
<xsl:attribute name="id">1</xsl:attribute>
<xsl:element name="author">author1</xsl:element>
<xsl:element name="title">title1</xsl:element>
</xsl:element>
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
有什么建议吗?
答案 0 :(得分:3)
使用apply-templates
:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@id">
<xsl:attribute name="id">2</xsl:attribute>
</xsl:template>
<xsl:template match="book">
<book id="1">
<author>author1</author>
<title>title1</title>
</book>
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:copy-of select="node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
您需要添加
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
确保未更改目录元素或其他元素和属性。
所以所有建议一起产生模板
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@id">
<xsl:attribute name="id">2</xsl:attribute>
</xsl:template>
<xsl:template match="book">
<book id="1">
<author>author1</author>
<title>title1</title>
</book>
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:copy-of select="node()"/>
</xsl:copy>
</xsl:template>
然后我们可以将代码缩短为
<xsl:template match="@*|node()" name="identity">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@id">
<xsl:attribute name="id">2</xsl:attribute>
</xsl:template>
<xsl:template match="book">
<book id="1">
<author>author1</author>
<title>title1</title>
</book>
<xsl:call-template name="identity"/>
</xsl:template>