Edw*_*alk 5 python xml elementtree
给定一个如下所示的 xml 文件:
<?xml version="1.0" encoding="windows-1252"?>
<Message xmlns="http://example.com/ns" xmlns:myns="urn:us:gov:dot:faa:aim:saa">
<foo id="stuffid"/>
<myns:bar/>
</Message>
Run Code Online (Sandbox Code Playgroud)
当我用 ElementTree 解析它时,元素标签看起来像:
<?xml version="1.0" encoding="windows-1252"?>
<Message xmlns="http://example.com/ns" xmlns:myns="urn:us:gov:dot:faa:aim:saa">
<foo id="stuffid"/>
<myns:bar/>
</Message>
Run Code Online (Sandbox Code Playgroud)
但我宁愿只是
{http://example.com/ns}Message
{http://example.com/ns}foo
{urn:us:gov:dot:faa:aim:saa}bar
Run Code Online (Sandbox Code Playgroud)
更重要的是,我宁愿将“Message”、“foo”和“bar”传递给find()和findall()方法。
我已经尝试使用替换来审查/sf/answers/1094892361/ 中xmlns:建议的所有属性(如果我找不到更优雅的东西,这可能是我必须做的),并且我试过打电话,但这似乎只对 有帮助,这不是我想要的。ElementTree.register_namespace('', "http://example.com/ns")ElementTree.tostring()
难道没有办法让 ElementTree 假装它从未听说过xmlns吗?
让我们假设即使没有命名空间限定符,我的元素标签也是全局唯一的。在这种情况下,命名空间只是碍手碍脚。
详细处理一些评论:
Joe 链接到Python ElementTree 模块:How to ignore the namespace of XML files to locate matching element when using the method "find", "findall"这与我的问题非常接近,我猜我的问题是重复的。然而,这个问题也没有得到回答。那里给出的建议是:
tree.findall("xmlns:DEAL_LEVEL/xmlns:PAID_OFF", namespaces={'xmlns': 'http://www.test.com'}).
register_namespace("", "http://example.com/ns")
ElementTree.tostring(el)但不在el.tag. 我希望它没有帮助,find()或者也没有findall()。好的,感谢您提供其他问题的链接。我决定借用(并改进)那里给出的解决方案之一:
def stripNs(el):
'''Recursively search this element tree, removing namespaces.'''
if el.tag.startswith("{"):
el.tag = el.tag.split('}', 1)[1] # strip namespace
for k in el.attrib.keys():
if k.startswith("{"):
k2 = k.split('}', 1)[1]
el.attrib[k2] = el.attrib[k]
del el.attrib[k]
for child in el:
stripNs(child)
Run Code Online (Sandbox Code Playgroud)