繁体   English   中英

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

[英]Python: Parse SVG / XML with namespace

在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>

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

解决方案是使用带有预定义命名空间数组前缀的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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM