【问题标题】:Replacing information within XML tags替换 XML 标记中的信息
【发布时间】:2019-12-28 03:41:48
【问题描述】:

我正在尝试使用 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 问题表明这是最好的主意。

【问题讨论】:

  • 可能仍然使用 ElementTree 而不是 beautifulsoup(为什么在 SVG 是格式良好的 XML 时使用 beautifulsoup??),但 SVG 通常位于默认命名空间中,因此您只需要针对那个。
  • @DanielHaley 你能扩展一下吗?我没有使用 ElementTree 的经验,而 BeautifulSoup 被证明会对 SVG 产生不利影响
  • 当然。您有更完整的 SVG 示例吗? (至少,你能给我“svg”开始标签,至少让我可以看到任何 xmlns 吗?)
  • for iten in 然后print(item) - 当然它什么也没找到 使用一个好的IDE,它会为你找到这样的错误。

标签: python xml svg elementtree


【解决方案1】:

正如您在问题中所说,您没有设置为使用 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 属性的&lt;tspan&gt; 标签。然后我们检查属性x 是否为'0 71.891571 154.0006 188.22296 256.66766'。如果是,我们将其设置为0

【讨论】:

  • 然后我需要将其输出写入一个新文件吗?我需要对 ~150 个 SVG 文件执行此操作
  • @JonathanDyke 是的,现在它在内存中发生了变化。然后,您可以将汤写入文件。使用循环更改约 150 个文件:每次迭代将文件的内容加载到汤,选择 tspan 标签,更改它们并将汤写回文件。
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 2013-11-19
  • 2011-01-07
  • 2013-05-04
  • 2019-01-09
  • 1970-01-01
  • 2022-12-23
  • 1970-01-01
相关资源
最近更新 更多