【问题标题】:Python: Ignore xmlns in elementtree.ElementTreePython:忽略 elementtree.ElementTree 中的 xmlns
【发布时间】:2012-06-27 12:30:26
【问题描述】:

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

我尝试打印所有technicalContact 标签:

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

我得到类似的东西:

{http://www.example.com}technicalContact blah@example.com

但我真正想要的是:

technicalContact blah@example.com

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

【问题讨论】:

标签: python xml xml-namespaces elementtree


【解决方案1】:

您可以定义一个生成器以递归方式搜索您的元素树,以便找到以适当标签名称结尾的标签。例如,像这样:

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

【讨论】:

  • 希望以上回答了这个问题。我注意到的一个区别是生成器示例中的item 没有next 方法。尽管如此,除此之外,它的行为方式与etree.getiterator 相同(相似?)。
【解决方案2】:

我总是最终使用类似的东西

item.tag.split("}")[1][0:]

【讨论】:

  • 它没有解决迭代器问题 - 我仍然需要遍历完整的标签名称。
  • 我不知道有什么不同的 xml 处理程序可以做到这一点。使用 lxml,您可以在解析之前在 xml 上使用 xlst。
  • [0:] 毫无意义。如果您想获取它的副本以免更改原件,您可以简单地执行[:]。或者,如果这不是问题,只需完全删除 [0:]
猜你喜欢
  • 2012-02-20
  • 1970-01-01
  • 2013-06-15
  • 2013-07-08
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
  • 2018-06-22
相关资源
最近更新 更多