0

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>
2
  • 1
    Good Minimal, Complete, and Verifiable example. +1 Commented Feb 26, 2019 at 15:29
  • Thank you for the input. Commented Feb 26, 2019 at 18:06

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.