Gab*_*ley 18 python xml namespaces elementtree
默认情况下,当您调用ElementTree.parse(someXMLfile)时,Python ElementTree库会为每个已解析的节点添加前缀,并在Clark的Notation中使用它的命名空间URI:
{http://example.org/namespace/spec}mynode
这使得在代码中稍后按名称访问特定节点非常痛苦.
我已经阅读了有关ElementTree和命名空间的文档,看起来该iterparse()函数应该允许我改变解析器前缀命名空间的方式,但对于我的生活,我实际上无法让它改变前缀.似乎在ns-start事件发生之前可能会在后台发生这种情况,如下例所示:
for event, elem in iterparse(source):
if event == "start-ns":
namespaces.append(elem)
elif event == "end-ns":
namespaces.pop()
else:
...
Run Code Online (Sandbox Code Playgroud)
如何更改前缀行为以及函数结束时返回的内容是什么?
你没有特别需要使用iterparse.相反,以下脚本:
from cStringIO import StringIO
import xml.etree.ElementTree as ET
NS_MAP = {
'http://www.red-dove.com/ns/abc' : 'rdc',
'http://www.adobe.com/2006/mxml' : 'mx',
'http://www.red-dove.com/ns/def' : 'oth',
}
DATA = '''<?xml version="1.0" encoding="utf-8"?>
<rdc:container xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:rdc="http://www.red-dove.com/ns/abc"
xmlns:oth="http://www.red-dove.com/ns/def">
<mx:Style>
<oth:style1/>
</mx:Style>
<mx:Style>
<oth:style2/>
</mx:Style>
<mx:Style>
<oth:style3/>
</mx:Style>
</rdc:container>'''
tree = ET.parse(StringIO(DATA))
some_node = tree.getroot().getchildren()[1]
print ET.fixtag(some_node.tag, NS_MAP)
some_node = some_node.getchildren()[0]
print ET.fixtag(some_node.tag, NS_MAP)
Run Code Online (Sandbox Code Playgroud)
产生
('mx:Style', None)
('oth:style2', None)
其中显示了如何访问已解析树中各个节点的完全限定标记名称.您应该能够根据您的特定需求进行调整.
| 归档时间: |
|
| 查看次数: |
9590 次 |
| 最近记录: |