Python 的 ElementTree 是否只允许一个命名空间映射?
Does Python's ElementTree allow only one namespace mapping?
我对 ElementTree 对命名空间映射的命名空间处理感到困惑。我需要解析具有不同默认名称空间的各种树。 ElementTree 似乎保留了我在 find() 中指定的第一个命名空间映射。
在下面的代码中,我希望在找到 D 时第二次传递给 barf,因为 D 不在传递的命名空间中找到()。相反,它 does 找到 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() 使用正确的命名空间映射?
环境:Mac OS X,Python 2.7.14 |Anaconda 自定义(64 位)
您遇到了 Python 3.3 中已修复但未在 Python 2.7 中修复的错误:https://bugs.python.org/issue17011 ("ElementPath ignores different namespace mappings for the same path expression").
当使用 Python 3.7 时,确实是 D
元素导致了 AssertionError。
我对 ElementTree 对命名空间映射的命名空间处理感到困惑。我需要解析具有不同默认名称空间的各种树。 ElementTree 似乎保留了我在 find() 中指定的第一个命名空间映射。
在下面的代码中,我希望在找到 D 时第二次传递给 barf,因为 D 不在传递的命名空间中找到()。相反,它 does 找到 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() 使用正确的命名空间映射?
环境:Mac OS X,Python 2.7.14 |Anaconda 自定义(64 位)
您遇到了 Python 3.3 中已修复但未在 Python 2.7 中修复的错误:https://bugs.python.org/issue17011 ("ElementPath ignores different namespace mappings for the same path expression").
当使用 Python 3.7 时,确实是 D
元素导致了 AssertionError。