You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XSLT中删除文档内属性值仅为数字的@id属性

Remove @id Attributes with Numeric-Only Values in XSLT

Here's a clean solution to strip out any @id attributes where the value is purely numeric, while leaving all other @id attributes (and the rest of your XML) untouched.

XSLT 2.0+ Version

This uses regular expressions for a concise check:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- Identity template: copies everything by default -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!-- Match and discard @id attributes that are only digits -->
    <xsl:template match="@id[matches(., '^\d+$')]"/>
</xsl:stylesheet>

Breakdown:

  • The identity template is the backbone here—it copies every node and attribute unless we explicitly say otherwise.
  • The second template targets @id attributes where the entire value matches ^\d+$ (one or more digits, nothing else). Since we don't output anything in this template, those attributes get dropped from the final XML.

XSLT 1.0 Version

If you're stuck with XSLT 1.0 (no regex support), use the translate() function to check for numeric-only values:

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

    <!-- Remove @id attributes with only digits (XSLT 1.0 compatible) -->
    <xsl:template match="@id[translate(., '0123456789', '') = '']"/>
</xsl:stylesheet>

Breakdown:

  • translate(., '0123456789', '') removes all digits from the attribute value. If the result is an empty string, that means the original value was nothing but digits—so we exclude that @id attribute.

Example Result

Given your input XML:

<?xml-stylesheet type="text/xsl" href="recursion2.xsl" ?>
<list>
  <book id="B1">
    <label>1</label>
    <title id="1">A Good Story</title>
    <author>James Soul</author>
  </book>
  <book id="B2">
    <label>...</label>
  </book>
</list>

The output will be:

<list>
  <book id="B1">
    <label>1</label>
    <title>A Good Story</title>
    <author>James Soul</author>
  </book>
  <book id="B2">
    <label>...</label>
  </book>
</list>

The <title> element loses its numeric id attribute, while the non-numeric ids on the <book> elements stay exactly as they are.

内容的提问来源于stack exchange,提问作者LearnAWK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:24:34