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

标签 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>

有什么建议吗?

最佳答案

使用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>

关于xml - 如何添加具有新 ID 的第二个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34548895/

相关文章:

java - 如何使用多个输入的任何循环指定输入目录?

xml - 如何使用 XSLT 重新格式化具有相关元素组的 XML

javascript - 从 XSLT 调用函数错误 : Namespace does not contain any functions

java - 来自 Fragment 的 Android 对话框

android - Tabhost 教程坏了?

android - 如何在布局中使用自己的 View ?

xml - 将 XML 元素的名称替换为属性的值

xslt - 使用 XSLT 删除 XML 模式中多余的复杂类型

java - 我可以在 Java 中根据 XSD 片段验证 XML 文件吗

java - 如何使用 XStream 为同一类元素设置不同的别名