1
2008
141100
4
2011
59900
68
2011
13600
/data
/data/country
/data/country@name Liechtenstein
/data/country/rank 68
/data/country/year 2011
/data/country/gdppc 13600
/data/country/neighbor
/data/country/neighbor@direction E
/data/country/neighbor@name Austria
我有一个简单的XML像上面,我需要打印的XML如下图所示的是XML的treeNode的,即时通讯在python初学者,不知道如何实现这一目标,请有人可以帮助,在此解决
提前致谢
最佳答案 我不知道任何直接的API可以给你结果,但你可以递归打印每个节点及其属性,然后得到它的孩子,并在那里做同样的事情.
示例 –
def walker(root, str):
print(str+root.tag, (root.text and root.text.strip()) or '')
for attrib in root.attrib:
print(str+root.tag+'@'+attrib,root.attrib[attrib])
for child in root:
walker(child,str+root.tag+'/')
对于像下面的xml –
>>> s = """<?xml version="1.0"?>
...
...
... 1
... 2008
... 141100
...
...
...
...
... 4
... 2011
... 59900
...
...
...
... 68
... 2011
... 13600
...
...
...
... """
>>>
>>>
>>> import xml.etree.ElementTree as ET
>>> r = ET.fromstring(s)
这给了我 –
>>> walker(r,'/')
/data
/data/country
/data/country@name Liechtenstein
/data/country/rank 1
/data/country/year 2008
/data/country/gdppc 141100
/data/country/neighbor
/data/country/neighbor@direction E
/data/country/neighbor@name Austria
/data/country/neighbor
/data/country/neighbor@direction W
/data/country/neighbor@name Switzerland
/data/country
/data/country@name Singapore
/data/country/rank 4
/data/country/year 2011
/data/country/gdppc 59900
/data/country/neighbor
/data/country/neighbor@direction N
/data/country/neighbor@name Malaysia
/data/country
/data/country@name Panama
/data/country/rank 68
/data/country/year 2011
/data/country/gdppc 13600
/data/country/neighbor
/data/country/neighbor@direction W
/data/country/neighbor@name Costa Rica
/data/country/neighbor
/data/country/neighbor@direction E
/data/country/neighbor@name Colombia