简体   繁体   中英

How do I loop through XML and print properly using elementtree in python?

I am getting every childtwo in the whole xml printed with every childone in the whole document. How do I get just the childtwos that go with the childone?

import xml.etree.ElementTree as ET            
tree = ET.parse("C:/Users/thisuser/Desktop/test.xml")
root = tree.getroot()

for ticket in root.findall('.//Parent'):
    Childone = ticket.find('.//Childone').text

    for ticket in root.findall('.//ParentTwo'):
        Childtwo = ticket.find('.//Childtwo').text

        print "Childone={Childone}, Childtwo={Childtwo}".format(Childone=Childone, Childtwo=Childtwo)

Result

ChildOne=1  ChildTwo=a
ChildOne=1  ChildTwo=b
ChildOne=1  ChildTwo=c
ChildOne=1  ChildTwo=d

ChildOne=2  ChildTwo=a
ChildOne=2  ChildTwo=b
ChildOne=2  ChildTwo=c
ChildOne=2  ChildTwo=d

Desired Result

ChildOne=1  ChildTwo=a
ChildOne=1  ChildTwo=b

ChildOne=2  ChildTwo=c
ChildOne=2  ChildTwo=d

XML sample

<Parent>
    <Childone>1</Childone>
        <ParentTwo>
            <Childtwo>a</Childtwo>
        </ParentTwo>
        <ParentTwo>
            <Childtwo>b</Childtwo>
        </ParentTwo>
</Parent>

<Parent>
    <Childone>2</Childone>
        <ParentTwo>
            <Childtwo>c</Childtwo>
        </ParentTwo>
        <ParentTwo>
            <Childtwo>d</Childtwo>
        </ParentTwo>
</Parent>

The issue is that you're using root in the findall of your second for loop:

for ticket in root.findall('.//ParentTwo'):

Instead, you should use ticket from the outer loop to limit what ParentTwo elements are found. (Also note I changed ticket to ticket2 since you've already used ticket .):

for ticket2 in ticket.findall('.//ParentTwo'):

Full edited code...

import xml.etree.ElementTree as ET
tree = ET.parse("C:/Users/thisuser/Desktop/test.xml")
root = tree.getroot()

for ticket in root.findall('.//Parent'):
    Childone = ticket.find('.//Childone').text

    for ticket2 in ticket.findall('.//ParentTwo'):
        Childtwo = ticket2.find('.//Childtwo').text

        print "Childone={Childone}, Childtwo={Childtwo}".format(Childone=Childone, Childtwo=Childtwo)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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