ElementTree 对命名空间映射的命名空间处理让我感到困惑。我需要解析具有不同默认 namespace 的各种树。 ElementTree 似乎保留了我在 find() 中指定的第一个 namespace 映射。
在下面的代码中,我希望第二次查找 D 时会失败,因为 D 不在传递给 find() 的命名空间中。相反,它确实找到了D(它有错误的命名空间),但在B(它应该找到)上失败了。
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
# Run code for two namespaces
namespaces = [ "http://www.example.org/X", "http://www.example.org/Y"]
for ns in namespaces:
try:
# make an XML document as a string
xmlString='''
<A xmlns="{ns}" xmlns:static="http://www.example.org/X">
<B>
<C>sam</C>
</B>
<static:D>
<C>sam</C>
</static:D>
</A>
'''.format(ns=ns)
print(xmlString)
tree = ET.fromstring(xmlString)
# See what namespace is used for the root element
print("treetag: {}".format(tree.tag))
# Find the element with the explicit namespace
elementD = tree.find("ns0:D", { "ns0":ns})
assert elementD != None, "elementD not found"
print("elementD: {}".format(elementD.tag))
# Find the element with the default namespace
elementB = tree.find("ns0:B", { "ns0":ns})
assert elementB != None, "elementB not found"
print("elementB: {}\n".format(elementB.tag))
except AssertionError as e:
print repr(e)
我的代码有什么问题吗?如果没有,我如何强制 find() 使用正确的 namespace 映射?
环境:Mac OS X、Python 2.7.14 |Anaconda 自定义(64 位)
最佳答案
您遇到了一个在 Python 3.3 中已修复但在 Python 2.7 中未修复的错误:https://bugs.python.org/issue17011 (“ElementPath 忽略同一路径表达式的不同命名空间映射”)。
当使用Python 3.7时,确实是D
元素导致了AssertionError。
关于python - Python 的 ElementTree 是否只允许一个 namespace 映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53433051/