xslt - 如何将 xslt for-each 应用于属性?

标签 xslt saxon

我的 XML 文档如下所示 -

<doc>

  <system_data>
    <registry_item id="1">
      <hive>HKEY_LOCAL_MACHINE</hive>
    </registry_item>
    <file_item id="2">
      <filepath>C:\Windows\System32\msasn1.dll</filepath>    
    </file_item>
  </system_data>

</doc>

我想对其进行转换,例如“id”属性值按顺序递增,例如:

<doc>

  <system_data>
    <registry_item id="10">
      <hive>HKEY_LOCAL_MACHINE</hive>
    </registry_item>
    <file_item id="11">
      <filepath>C:\Windows\System32\msasn1.dll</filepath>    
    </file_item>
  </system_data>

</doc>

我使用“identity ”设计,我的 xsl 看起来像这样 -

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:xslt="http://www.w3.org/1999/XSL/Transform">
<xsl:import href="Identity.xsl"/>
<xslt:param name="newID" />
  <xsl:template match="//system_data/*">
      <xsl:for-each select="@id">
        <xsl:attribute name="id">
            <xsl:value-of select="number($newID)+1"/>      
        </xsl:attribute>
      </xsl:for-each>   
  </xsl:template> 
</xsl:stylesheet>

我将 newID 值传递为“10”。如何选择每个属性并增加其值?

Indentity.xsl 看起来像这样 -

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <!-- Whenever you match any node or any attribute -->
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

当我应用 xsl 时,出现以下错误 -

An attribute node (id) cannot be created after the children of the containing element

最佳答案

尝试将 match="//system_data/*" 的模板更改为:

  <xsl:template match="@id">
    <xsl:attribute name="id">
      <xsl:value-of select="number($newID)+count(preceding::*/@id)"/>
    </xsl:attribute>
  </xsl:template>

关于xslt - 如何将 xslt for-each 应用于属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9835101/

相关文章:

xslt - 将 XSLT 应用于 XML 文件

java - 验证失败后移动文件 (Java)

java - 使用 Saxon 通过 XSLT 生成 URL

c# - 在 ASP.NET Core 应用程序中未解析 Saxon 的 Nuget 包的引用

xslt - 撒克逊 CE 和 XQuery?文档表明没有 XQuery,否则有示例吗?

xml - 如何使用 match 属性获取具有特定名称的所有节点

xml - 使用 XML 和 XSLT 进行树形导航

xml - XSLT 从 REST API 转换 XML

javascript - 使用 XSLT 渲染 xhtml 兼容页面将无法正确渲染过去的内联 javascript block

java - 使用 saxon 获取远程 XML