简体   繁体   English

使用ElementTree解析XML

[英]Parse XML with ElementTree

I'm trying to parse a xml with the below content 我正在尝试解析具有以下内容的xml

<File version="5.6">
<Parent name="A">
<Child name="a"/>
<Child name="b"/>
</Parent>

<Parent name="B">
<Child name="c"/>
<Child name="d"/>
</Parent>

<Parent name="C">
<Child name="e"/>
<Child name="f"/>
</Parent>

</File>

And I used the following code 我用下面的代码

for child in tree.getroot().findall('./Parent/Child')
     print child.attrib.get("name")

It just print all the name of children without the parent names. 它只打印所有孩子的名字而没有父母的名字。 Can I print the relevant parent name of each child like this? 我可以像这样打印每个孩子的相关父母姓名吗?

A has a b
B has c d
C has e f

Iterate over parents, then find children of the parents. 遍历父母,然后找到父母的孩子。

for parent in tree.findall('./Parent'):
    children = [child for child in parent.findall('./Child')]
    print '{} has {}'.format(parent.get('name'), ' '.join(c.get('name') for c in children))

Response to the comment 对评论的回应

Using lxml, you can access parent node with getparent() method. 使用lxml,可以使用getparent()方法访问父节点。

import lxml.etree
tree = lxml.etree.parse('1.xml')
for child in tree.findall('./Parent/Child'):
    print '{} has {}'.format(child.getparent().get('name'), child.get('name'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM