lxml
存储具有完整名称空间URI的所有限定名,例如
from lxml import etree
root = etree.fromstring('''
<a:doc xmlns:a="http://somesite.org/markup" xmlns:b="http://anothersite.org/markup" a:attr="foo">
<b:e b:attr="bar"/>
</a:doc>''')
for el in root.iter():
print("Element", el.tag)
for a in el.attrib:
print(" Attribute", a)
将打印
Element {http://somesite.org/markup}doc
Attribute {http://somesite.org/markup}attr
Element {http://anothersite.org/markup}e
Attribute {http://anothersite.org/markup}attr
但是,如果我需要更多具有名称空间前缀而不是uri的可读输出呢?就像
Element a:doc
Attribute a:attr
Element b:e
Attribute b:attr
当然,我可以自己写转换函数
def uri2prefix(name, nsmap):
qname = etree.QName(name)
for pref, uri in nsmap.items():
if qname.namespace == uri:
return pref + ':' + qname.localname
return name
for el in root.iter():
print("Element", uri2prefix(el.tag, el.nsmap))
for a in el.attrib:
print(" Attribute", uri2prefix(a, el.nsmap))
但是在lxml
中一定有相同的功能,因为lxml.etree.tostring()
使用它。不幸的是,我在文档中找不到它。也许有人知道做这项工作的神奇功能?你知道吗
我看没有比使用uri2prefix函数更好的解决方案了。你知道吗
唯一的改进是元素:
_Element
实例有一个前缀属性。所以,你可以这样改变你的循环:相关问题 更多 >
编程相关推荐