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

使用xml.etree.ElementTree实现SVG title换行且文件无实际换行

实现SVG Tooltip换行且保持文件单行格式

用Python的xml.etree.ElementTree生成SVG时,需要实现两个核心需求:

  • 鼠标悬停<path>元素时,tooltip(对应<title>标签内容)显示换行效果
  • SVG文件中每个<path>元素保持单行结构,不出现实际换行符

之前尝试用&#10;或&#xA;替代\n,但ElementTree.write()会自动转义&,最终文件中变成&amp;#10;,无法触发换行;直接用\n则会让文件中出现实际换行,破坏<path>的单行结构。原示例代码如下:

import xml.etree.ElementTree as ET

svg = ET.Element('svg', xmlns="http://www.w3.org/2000/svg")
elem = ET.Element("path", {"class":"grp8", "d":"m 853.54468..."})
title = ET.Element("title")
# title.text = "Thomas Cazenave\n1e circo..." # 文件中出现实际换行符
title.text = "Thomas Cazenave&#xA;1e circo..." # &被转义,tooltip无换行
elem.append(title)
svg.append(elem)

tree = ET.ElementTree(svg)
with open("./frencharch.svg", "wb") as f:
    tree.write(f, encoding="utf-8", xml_declaration=True)

解决方法

核心思路是:先用Python原生\n定义<title>中的换行逻辑,再将序列化后的XML字符串里的实际换行符替换为XML实体&#10;,既保证文件单行结构,又能让tooltip解析出换行效果。

修改后的代码:

import xml.etree.ElementTree as ET

svg = ET.Element('svg', xmlns="http://www.w3.org/2000/svg")
elem = ET.Element("path", {"class":"grp8", "d":"m 853.54468..."})
title = ET.Element("title")
# 用Python原生换行符定义文本换行
title.text = "Thomas Cazenave\n1e circo. Gironde"
elem.append(title)
svg.append(elem)

# 将XML序列化为字符串
xml_content = ET.tostring(svg, encoding='utf-8', xml_declaration=True).decode('utf-8')
# 替换文本中的实际换行符为XML实体
xml_content = xml_content.replace('\n', '&#10;')

# 写入文件
with open("./frencharch.svg", "w", encoding="utf-8") as f:
    f.write(xml_content)

效果说明

  • 生成的SVG文件中,<path>元素保持单行,<title>内容为Thomas Cazenave&#10;1e circo. Gironde,无实际换行符
  • 鼠标悬停<path>时,浏览器会将&#10;解析为换行,tooltip正常显示两行文本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:47:53