通过 xslt 更改 XML 属性的值

lei*_*ood 2 xml xslt attributes

我有以下 xml 文件:

<Book description="for beginners" name="IT Book">
    <Available>yes</Available>
    <Info pages="500.</Info>
</Book>
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像这样:

<Book description="for pros" name="IT Book">
    <Available>yes</Available>
    <Info pages="500.</Info>
</Book>
Run Code Online (Sandbox Code Playgroud)

我在互联网上查找了如何正确修改 xml 文档。我发现首先我应该声明一个模板来复制所有内容:

<xsl:template match="node() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

但是,我不知道如何编写实际修改的模板。感谢您帮助初学者。

编辑:到目前为止,这是我的样式表(根据 uL1 的要求):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:sig="http://www.w3.org/2000/09/xmldsig#">
    <xsl:output indent="yes" method="xml" omit-xml-declaration="yes"/>

    <xsl:template match="node() | @*">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="@description='for beginners'">
        <xsl:attribute name="{name()}">
            <xsl:text>for pros</xsl:text>
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

uL1*_*uL1 5

这个问题已经在许多其他线程中得到了回答。例如。XSLT:如何在 <xsl:copy> 期间更改属性值?

在您的情况下,description除了身份副本模板之外,您还需要一个与您的属性匹配的模板。

<xsl:template match="@description"> <!-- @ matches on attributes, possible to restrict! -->
  <xsl:attribute name="{name()}">   <!-- creates a new attribute with the same name -->
    <xsl:text>for pros</xsl:text>   <!-- variable statement to get your desired value -->
  </xsl:attribute>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

编辑 1(导致错误的更多信息)

一个完整的、有效的、可运行的脚本是:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@description[. = 'for beginners']">
    <xsl:attribute name="{name()}">
      <xsl:text>for pros</xsl:text>
    </xsl:attribute>
  </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)