替换XML标记中的信息

2024-04-27 16:24:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用ElementTree替换SVG文件中的信息,但是我对它非常陌生,没有取得太大的进展

到目前为止,我的代码是:

import xml.etree.ElementTree as ET

tree = ET.parse('path-to-file')
root = tree.getroot()
for item in root.iter('tspan'):
    print(item)

但是这没有找到任何东西。
我尝试查找的SVG文件信息的格式如下:

<text
     transform="matrix(0,-1,-1,0,2286,3426)"
     style="font-variant:normal;font-weight:normal;font-size:123.10199738px;font-family:Arial;-inkscape-font-specification:ArialMT;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
     id="text79724">
  <tspan
     x="0 71.891571 154.0006 188.22296 256.66766"
     y="0"
     sodipodi:role="line"
     id="tspan79722">&lt;SI1&gt;</tspan>
</text>

我特别想改变

x="0 71.891571 154.0006 188.22296 256.66766" 

x="0"

我不打算使用ElementTree来做这件事,但是,大多数类似的StackOverflow问题表明这是最好的主意


Tags: 文件textsvg信息idtreerootitem
1条回答
网友
1楼 · 发布于 2024-04-27 16:24:07

如您在问题中所述,您没有设置为使用ElementTree-因此这里有一个使用beautifulsoup的解决方案:

data = '''<text
           transform="matrix(0,-1,-1,0,2286,3426)"
           style="font-variant:normal;font-weight:normal;font-size:123.10199738px;font-family:Arial;-inkscape-font-specification:ArialMT;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
           id="text79724"><tspan
             x="0 71.891571 154.0006 188.22296 256.66766"
             y="0"
             sodipodi:role="line"
             id="tspan79722">&lt;SI1&gt;</tspan></text>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'html.parser')

for tspan in soup.select('tspan[x]'):
    if tspan['x'] == '0 71.891571 154.0006 188.22296 256.66766':
        tspan['x'] = 0

print(soup.prettify())
#if writing to a new svg file, use soup instead of soup.prettify()

印刷品:

<text id="text79724" style="font-variant:normal;font-weight:normal;font-size:123.10199738px;font-family:Arial;-inkscape-font-specification:ArialMT;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none" transform="matrix(0,-1,-1,0,2286,3426)">
 <tspan id="tspan79722" sodipodi:role="line" x="0" y="0">
  &lt;SI1&gt;
 </tspan>
</text>

CSS选择器tspan[x]将选择带有属性x<tspan>标记。然后我们检查属性x是否是'0 71.891571 154.0006 188.22296 256.66766'。如果是,我们将其设置为0

相关问题 更多 >