1

I have xml:

<tree-root>
<sub1>it is sub1</sub1>
    <sub2>
    <sub3>sub3</sub3>
    <position>5584</position>
    <source-IP>
    <address-IP>2.104.54.11</address-IP>
    <address-IP>172.16.33.11</address-IP>
   </source-IP>
</sub2>

I would like to parse all the children inside of source-IP. The output shall be both IPs not just one. I would like to have :

2.104.54.11
172.16.33.11

It is similar to Parse XML with Python when multiple children share a name, but I would kindly ask for all the code.

Thank you in advance.

I have tried print(tree.find('sub2').find('source-IP').findall('address-IP').text);, but only bringing the error:

'list' object has no attribute 'text'

Here is the full code:

print(tree.find('sub2').find('source-IP').find('address-IP').text)

{    import xml.etree.ElementTree as ET  
tree = ET.parse('IPs.xml')  
root = tree.getroot()


print(root.text)
print(tree.find('sub1').text)                         
print(tree.find('sub2').find('sub3').text)  
print(tree.find('sub2').find('position').text)
 print('I would like to print all the IPs below, not just the first one')
print(tree.find('sub2').find('source-IP').find('address-IP').text)
print(tree.find('sub2').find('source-IP').find('address-IP').text)
}

1 Answer 1

1

.findall() returns a list of items. You need to loop over each of those items to get the text:

for address_ip in tree.find('sub2').find('source-IP').findall('address-IP'):
    print address_ip.text
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.