对于xml
<grandparent>
<parent1>
<child>data1</child>
</parent1>
<parent2>
<child>data2</child>
</parent2>
</grandparent>我需要包含父元素的元组的列表,xml中每个父元素的数据。
有没有办法用cElementTree做到这一点呢?我可以这样做,为孩子,数据,但不幸的是,孩子的所有值都是相同的,因此它没有太大的用处。
发布于 2008-12-17 13:46:41
似乎可以通过使用child.find('../parent')等xpath命令,使用ElementTree 1.3版(请检查http://effbot.org/zone/element-xpath.htm)从子进程访问父进程。但我认为python附带了1.2版或更高版本。
您还应该检查lxml,它与etree兼容,并且具有完全支持Xpath的http://lxml.de/。
发布于 2012-09-21 23:39:38
parent_map = dict((c, p) for p in tree.getiterator() for c in p)
parent_map[el].remove(el)发布于 2016-07-06 03:20:57
此语法似乎适用于cElementTree
ET.fromstring("<c><a><b></b></a></c>").find('.//b/..')不转到基本父级,并在路径中使用双斜杠和单斜杠。
(我本想在上面的帖子上发表评论,但似乎我没有特权)
https://stackoverflow.com/questions/374245
复制相似问题