1

我正在尝试使用以下内容解析 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>

我使用了以下代码

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

它只打印没有父母姓名的所有孩子的姓名。我可以这样打印每个孩子的相关父母姓名吗?

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

1 回答 1

2

遍历父母,然后找到父母的孩子。

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))

对评论的回应

使用 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'))
于 2013-08-14T09:37:01.780 回答