如何用XSLT移除XML属性中指定子字符串
XSLT修改XML属性路径的解决方案
正确实现代码
针对你需要修改的XML属性规则,这里提供两种实现方式:
基础实现(直接匹配修改)
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 身份模板:默认复制所有节点与属性 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 处理element3的attribute属性 --> <xsl:template match="element3/@attribute"> <xsl:attribute name="attribute"> <!-- 拼接固定前缀和目标后缀 --> <xsl:value-of select="concat('X:\\a\\b\\c\\', substring-after(., '.xyz\\'))"/> </xsl:attribute> </xsl:template> </xsl:stylesheet>
严谨实现(增加规则校验)
如果需要只修改以X:\\a\\b\\c开头且以.xyz\\name.ext结尾的属性,可以添加条件判断:
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="element3/@attribute[starts-with(., 'X:\\a\\b\\c') and ends-with(., '.xyz\\name.ext')]"> <xsl:attribute name="attribute"> <xsl:value-of select="concat('X:\\a\\b\\c\\', substring-after(., '.xyz\\'))"/> </xsl:attribute> </xsl:template> </xsl:stylesheet>
原代码问题分析
你之前的代码之所以只得到name.ext,是因为两次使用substring-after:
- 第一次
substring-after(., 'X:\\a\\b\\c\\')得到的是any string.xyz\\name.ext - 第二次再对这个结果用
substring-after(., '\\'),就只剩下name.ext,完全丢失了需要保留的前缀X:\\a\\b\\c\\
示例验证
输入XML:
<?xml version="1.0" encoding="utf-8" ?> <element1> <element2> <element3 attribute="X:\\a\\b\\c\\any string.xyz\\name.ext" /> </element2> </element1>
输出XML:
<?xml version="1.0" encoding="utf-8" ?> <element1> <element2> <element3 attribute="X:\\a\\b\\c\\name.ext" /> </element2> </element1>
内容的提问来源于stack exchange,提问作者Johnny
相关产品推荐
相关产品推荐

