如何用XSLT向现有SVG文件中的图形递归添加文本?
XSLT批量添加SVG文本块解决方案
核心思路
通过身份模板保留原有SVG结构,精准匹配目标分组后插入指定格式的<text>元素,具体步骤如下:
1. 处理SVG命名空间
SVG元素默认属于http://www.w3.org/2000/svg命名空间,XSLT必须声明该命名空间才能正确匹配节点。
2. 完整XSLT示例
假设你的SVG结构如下(含目标分组):
<svg xmlns="http://www.w3.org/2000/svg"> <g id="symbols"> <g id="Item1-svg"> <path id="shape_rect" d="M10 10h100v100h-100z"/> </g> <g id="Item2-svg"> <path id="shape_circle" d="M60 60 r40"/> </g> <g id="NormalGroup"> <path id="shape_line" d="M10 10 L100 100"/> </g> </g> </svg>
对应的TextAddition.xsl代码:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:svg="http://www.w3.org/2000/svg"> <!-- 身份模板:复制所有未被特殊匹配的节点/属性,保留原有SVG结构 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 精准匹配symbols下ID为Item*-svg的分组 --> <xsl:template match="svg:g[@id='symbols']/svg:g[@id[starts-with(., 'Item') and ends-with(., '-svg')]]"> <xsl:copy> <!-- 复制当前分组的所有属性和原有节点(如path) --> <xsl:apply-templates select="@*|node()"/> <!-- 添加固定格式的text元素,内容取分组内path的ID --> <svg:text x="10" y="120" font-size="12" fill="#333" font-family="Arial"> <xsl:value-of select="svg:path/@id"/> </svg:text> </xsl:copy> </xsl:template> </xsl:stylesheet>
3. 关键细节说明
- 目标分组定位:用
svg:g[@id='symbols']/svg:g[@id[starts-with(., 'Item') and ends-with(., '-svg')]]精确筛选symbols下的目标分组,避免误匹配其他位置的<g>元素。 - 文本属性自定义:
<text>的x/y坐标、字体大小、颜色等可根据需求调整;如果分组内有多个<path>,可改用<xsl:for-each>循环输出所有ID:<xsl:for-each select="svg:path"> <svg:text x="10" y="{120 + position()*15}" font-size="12" fill="#333"> <xsl:value-of select="@id"/> </svg:text> </xsl:for-each> - 兼容性:代码基于XSLT 1.0编写,支持绝大多数SVG处理工具(如Saxon、Xalan等)。
内容的提问来源于stack exchange,提问作者Oran G. Utan
相关产品推荐
相关产品推荐

