4

我有,

<parent id="1">
    <child id="white"></child>
    <child id="red"></child>
</parent>
<parent id="2">
    <child id="green"></child>
    <child id="gray"></child>
</parent>

我需要这个输出,

1 
 white
 red
2
 green
 gray

我就是这样做的,

parent = xmldoc.getElementsByTagName('parent')
for item in parent:
    child = xmldoc.getElementsByTagName('child')
    child_id = child.getAttribute('id')
    for child_id in child:
        print child_id

当然,我弄错了,但不知道如何遍历这些父 ID 并单独收集每个列表。我会很感激一些帮助!

4

2 回答 2

2

Try this

import xml.dom.minidom as minidom

a = '<parent id="1"><child id="white"></child><child id="red"></child></parent>'
dom = minidom.parseString(a)

for parent in dom.childNodes:
    print parent.getAttribute('id')
    for child in parent.childNodes:
        print '  %s' % child.getAttribute('id')
于 2012-08-02T06:39:09.747 回答
1

因为您在猜测代码和语法:

import xml.dom.minidom

s =  """<?xml version="1.0"?>
<container>
<parent id="1">
    <child id="white"></child>
    <child id="red"></child>
</parent>
<parent id="2">
    <child id="green"></child>
    <child id="gray"></child>
</parent>
</container>
"""


xmldoc = xml.dom.minidom.parseString(s)

parent = xmldoc.getElementsByTagName('parent')
for item in parent:
    print item.getAttribute('id')
    for child in item.getElementsByTagName('child'):
        print child.getAttribute('id')
于 2012-08-02T06:42:17.493 回答