有没有办法在 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?
最佳答案
您可以定义一个生成器来递归搜索您的元素树,以找到以适当的标签名称结尾的标签。例如,像这样:
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
关于Python:忽略 elementtree.ElementTree 中的 xmlns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11226247/