【问题标题】:Iterating over grandchildren in XML Tree in Python在 Python 中迭代 XML 树中的孙子
【发布时间】:2020-02-05 21:22:47
【问题描述】:

这里有些东西不起作用,我正试图了解原因。我好像和xml.etree.ElementTree examples from the documentation很像,所以不太明白哪里错了。

假设我们有以下 XML 文件(SVG 字体文件的高度简化示例):

<?xml version="1.0" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
<metadata>Text</metadata>
<defs>
<font id="ID">
    <glyph glyph-name="G1" unicode="..." 
d="path" />
    <glyph glyph-name="G2" unicode="..." 
d="path" />
    <glyph glyph-name="G3" unicode="..." 
d="path" />
    <glyph glyph-name="G4" unicode="..." 
d="path" />
  </font>
</defs></svg>

现在,为什么这不返回任何东西?

In [1]: import xml.etree.ElementTree as ET
   ...:
   ...: tree = ET.parse('svg_font.xml')
   ...: root = tree.getroot()
   ...:
   ...: for glyph in root.findall('glyph'):
   ...:     print('Name: ' + glyph.attrib)
   ...:

In [2]:

感谢您为我提供了一些启示!

【问题讨论】:

  • 根据文档,element.findall() 仅查找给定元素的直接子元素。在您的文档中,&lt;glyph&gt; 标签不是根元素的直接子元素。

标签: python xml svg


【解决方案1】:

由于 svg 标记中的此声明 [xmlns="http://www.w3.org/2000/svg"],因此每个标记都应以 '{http://www.w3.org/2000/svg}' 命名空间

例如,使用“{http://www.w3.org/2000/svg}glyph”代替“glyph”

每个标签都应以'{http://www.w3.org/2000/svg}'为前缀

另外,不要使用“findall”,而是使用“iter”! 通过以下方式更改您的“for”循环

for glyph in El.iter('{http://www.w3.org/2000/svg}glyph'):
    print('Name: ' + str(glyph.attrib))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    相关资源
    最近更新 更多