python获取xml所有节点_如何使用python获取XML的所有子节点?

本文介绍了如何使用Python的xml.etree.ElementTree模块解析XML文件,并通过示例展示了获取XML根节点所有子节点的步骤,包括调用getchildren()方法和使用lambda函数遍历节点。

import xml.etree.ElementTree as ET

tree = ET.parse('country_data.xml')

root = tree.getroot()

country = root[0].getchildren()

map(lambda e: e.tag, r)

# ['rank', 'year', 'gdp', 'neighbor', 'neighbor']

顺便说一句,当你被卡住时,打开repl并一步一步地走。我不记得上面那些东西。最后一次使用xml解析器是在两三年前。但我知道,“试一试”是最好的老师。

这些都是我想出解决办法的步骤。# imports and other stuff.

>>> tree = ET.parse('data.xml')

>>> root = tree.getroot()

>>> country = root[0]

>>> dir(country)

['__class__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__len__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_children', 'append', 'attrib', 'clear', 'copy', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set', 'tag', 'tail', 'text']

>>> country.keys()

['name']

>>> country.getchildren()

[, , , , ]

>>> country.getchildren()[0]

>>> r = country.getchildren()[0]

>>> dir(r)

['__class__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__len__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_children', 'append', 'attrib', 'clear', 'copy', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set', 'tag', 'tail', 'text']

>>> r.tag

'rank'

>>> r = country.getchildren()[0]

>>> r

>>> r = country.getchildren()

>>> r

[, , , , ]

>>> map(lambda e: e.tag, r)

['rank', 'year', 'gdp', 'neighbor', 'neighbor']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值