1

我的 XML:

<animals>
  <animal name="fox" fullname="fullfox"></animal>
  <animal name="dog" fullname="halfdog"><food>milk</food><food>rice</food><food>meat</food>   </animal>
  <animal name="cow" fullname="doublecow"><food>grass</food></animal>
  <animal name="blabla" fullname="fullbla"></animal>
</animals>

我正在尝试解析这个 XML 以获得与输出相同的 XML。

doc    = ET.parse("an.xml")
root = doc.getroot() #Returns the root element for this tree.
root_new  = ET.Element("animals") 
for child in root:
    name = child.attrib['name']
    fullname = child.attrib['fullname']

for g in root.findall("*/food"):
    animal    = ET.SubElement(root_new, "animal") 
    food     = ET.SubElement(animal, "food")   
    food.text = g.text
    animal.set("name",name)               
    animal.set("fullname",fullname) 

tree = ET.ElementTree(root_new)
tree.write(sys.stdout)

但我只得到最后一个值

<animals>
  <animal fullname="fullbla" name="blabla"><food>milk</food></animal>
  <animal fullname="fullbla" name="blabla"><food>rice</food></animal>
  <animal fullname="fullbla" name="blabla"><food>meat</food></animal>
  <animal fullname="fullbla" name="blabla"><food>grass</food></animal>
</animals>

而且食物节点也错了,如何像我输入的 XML 一样进行迭代?

4

3 回答 3

2

你需要一个嵌套循环:

for child in root:
    name             = child.attrib['name']
    fullname         = child.attrib['fullname']
    # create "animal" here
    animal    = ET.SubElement(root_new, "animal") 
    animal.set("name",name)               
    animal.set("fullname",fullname)
    for g in child.findall("food"):
        # create "food" here
        food     = ET.SubElement(animal, "food")   
        food.text = g.text 
于 2012-11-05T08:25:56.753 回答
2

你的代码应该是这样的

doc    = ET.parse("test.xml")
root = doc.getroot() #Returns the root element for this tree.
root_new  = ET.Element("animals") 
for child in root:
    name             = child.attrib['name']
    fullname         = child.attrib['fullname']
    animal    = ET.SubElement(root_new, "animal") 
    animal.set("name",name)               
    animal.set("fullname",fullname) 

    for g in child.findall("food"):
        food = ET.SubElement(animal, "food")   
        food.text = g.text

tree = ET.ElementTree(root_new)
tree.write(sys.stdout)
于 2012-11-05T08:27:24.677 回答
1

有两个问题。第一个是你的缩进 - 我假设那些是嵌套循环。第二个问题是您正在使用root.findall,这意味着您将获取所有food项目,无论它们位于哪个节点。试试这个:

...
for child in root:
    name = child.attrib['name']
    fullname = child.attrib['fullname']
    animal = ET.SubElement(root_new, 'animal')
    for g in child.findall("food"):
        food = ET.SubElement(animal, "food")   
        food.text = g.text
        animal.set('name', name)               
        animal.set('fullname', fullname) 
于 2012-11-05T08:22:55.107 回答