python etree_一个etree对象所有元素的简单循环?

您面临的问题是您没有访问文件中的所有节点。您只访问elem元素的子元素,而不是访问这些元素的子元素。为了说明这一点,请运行以下命令(我已将XML编辑为有效):from xml.etree.ElementTree as etree

xml_string = """

"""

e = etree.fromstring(xml_string)

for node in e:

print node

结果

^{pr2}$

所以您没有访问节点if的子节点variable。您需要递归地访问XML文件中的每个节点,也就是说,您的函数collect_vars需要调用它自己。稍后我将发布一些代码来说明这一点。在

编辑:正如承诺的那样,一些代码可以从元素树中获取所有id属性。我用的是发电机,而不是像Niek de Klein那样使用蓄电池。这有很多优点。例如,这将一次返回一个id,因此您可以在任何时候停止处理,例如遇到某个{},这样可以节省对整个XML文件的读取。在def get_attrs(element, tag, attr):

"""Return attribute `attr` of `tag` child elements of `element`."""

# If an element has any cildren (nested elements) loop through them:

if len(element):

for node in element:

# Recursively call this function, yielding each result:

for attribute in get_attrs(node, tag, attr):

yield attribute

# Otherwise, check if element is of type `tag` with attribute `attr`, if so

# yield the value of that attribute.

if element.tag == 'variable':

if attr in element.attrib:

yield element.attrib[attr]

ids = [id for id in get_attrs(e, 'variable', 'id')]

print ids

这就产生了结果['getthis', 'alsoGetThis']

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值