【问题标题】:Python: Parse SVG / XML with namespacePython:使用命名空间解析 SVG / XML
【发布时间】:2019-11-06 07:41:57
【问题描述】:

在 Python 中解析 xml 文件(在本例中为 svg)很方便,但只要涉及命名空间,就没有任何作用。使用 Pythons xml 库的正确方法是什么?

如果我的文件没有命名空间,我可以轻松地执行以下代码并获取所有元素:

import xml.etree.ElementTree as ET
tree = ET.parse('model1.svg')  
root = tree.getroot()
lst = root.findall('g/g/g/g')
print(lst)

但是因为它有一个命名空间:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="temp" width="1809.6200256347656" height="1247.809829711914" version="1.1" viewBox="0 0 1809.6200256347656 1247.809829711914">

回复是:[]

如果我尝试打印 root 我会得到:

<Element '{http://www.w3.org/2000/svg}svg' at 0x7fbc45154ea8>

而不是这个:

<Element 'svg' at 0x7f8ee9377368>

所以我无法使用它。如何停用/忽略它?

【问题讨论】:

标签: python xml parsing svg namespaces


【解决方案1】:

解决方案是使用带有预定义命名空间数组前缀的 xml 标签(例如g):

import xml.etree.ElementTree as ET
tree = ET.parse('./model1.svg')
root = tree.getroot()

ns_array = {
    'svg': 'http://www.w3.org/2000/svg', 
    'xlink': 'http://www.w3.org/1999/xlink'
    }

lst = root.findall('svg:g/svg:g/svg:g/svg:g', ns_array)

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 2014-01-10
    • 2010-11-08
    • 2012-06-11
    相关资源
    最近更新 更多