如何使用lxml将名称空间URI转换为前缀?

2024-04-25 00:52:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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()使用它。不幸的是,我在文档中找不到它。也许有人知道做这项工作的神奇功能?你知道吗


Tags: inorghttpfordocattributerootelement
1条回答
网友
1楼 · 发布于 2024-04-25 00:52:29

我看没有比使用uri2prefix函数更好的解决方案了。你知道吗

唯一的改进是元素:_Element实例有一个前缀属性。所以,你可以这样改变你的循环:

for el in root.iter():
    name = el.prefix + ':' + etree.QName(el).localname if el.prefix else etree.QName(el).localname
    print("Element", name)
    for a in el.attrib:
        print("  Attribute", uri2prefix(a, el.nsmap))

相关问题 更多 >