Python:忽略 elementtree.ElementTree 中的 xmlns

2024-03-17

有没有办法忽略标记名称中的 XML 命名空间elementtree.ElementTree?

我尝试打印所有technicalContact tags:

for item in root.getiterator(tag='{http://www.example.com}technicalContact'):
        print item.tag, item.text

我得到类似的信息:

{http://www.example.com}technicalContact [email protected] /cdn-cgi/l/email-protection

但我真正想要的是:

technicalContact [email protected] /cdn-cgi/l/email-protection

有没有办法只显示后缀(无 xmlns),或者更好 - 迭代元素而不显式声明 xmlns?


您可以定义一个生成器来递归搜索元素树,以查找以适当标签名称结尾的标签。例如,这样的事情:

def get_element_by_tag(element, tag):
    if element.tag.endswith(tag):
        yield element
    for child in element:
        for g in get_element_by_tag(child, tag):
            yield g

这只是检查以结尾的标签tag,即忽略任何前导命名空间。然后您可以迭代任何您想要的标签,如下所示:

for item in get_element_by_tag(elemettree, 'technicalContact'):
    ...

该生成器正在运行:

>>> xml_str = """<root xmlns="http://www.example.com">
... <technicalContact>Test1</technicalContact>
... <technicalContact>Test2</technicalContact>
... </root>
... """

xml_etree = etree.fromstring(xml_str)

>>> for item in get_element_by_tag(xml_etree, 'technicalContact')
...     print item.tag, item.text
... 
{http://www.example.com}technicalContact Test1
{http://www.example.com}technicalContact Test2
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python:忽略 elementtree.ElementTree 中的 xmlns 的相关文章

随机推荐