Python:使用命名空间解析SVG / XML



Python中解析xml文件(在本例中为svg(很方便,但是一旦涉及命名空间,就没有任何效果。使用 Python 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>

所以我就是不能使用它。如何停用/忽略它?

解决方案是使用 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)

最新更新