如何添加具有新ID的第二个元素?

时间:2015-12-31 16:13:50

标签: xml xslt

这应该相当容易,但我是XSLT的新手,我很难找到解决方案。我得到了以下XML:

<catalog>
    <book id="1">
        <author>Mike</author>
        <title>Tomas</title>
    </book>
</catalog>

我正在尝试在其上添加另一个book条目,并将其id1更改为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>

有什么建议吗?

1 个答案:

答案 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>