python中 getnode用法_python中xml的GetTreeNode

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值