1

Good day dear developers. I can't fully parse an xml file.

The structure looks like:

<foo>
   <bar1 id="1">
      <bar2>
        <foobar id="2">name1</foobar>
        <foobar id="3">name2</foobar>
     </bar2>
   </bar1>
</foo>

I used the xml.etree library so I use code like:

source.get('Id')

so i get the first attribute

to get a nested tag i use code like: source.find('bar/foobar').text

The question is how to get next nested attributes? ( Id =2 and id = 3) It shows an error when i'm trying to use some stuff with slash source.get('bar/id') and other tries give me just the first attribute which i already got, also the second nested attribute has the same name Id.

Thank you for the help in advance.

1
  • You want us to help you, right? So don't say "It shows an error when I'm trying to use some stuff...". Tell us exactly what you did and exactly how it failed, and then we can help you. Commented Jan 1, 2020 at 22:12

3 Answers 3

1

Below is a working example

import xml.etree.ElementTree as ET

xml = '''<foo>
   <bar1 id="1">
      <bar2>
        <foobar id="2">name1</foobar>
        <foobar id="3">name2</foobar>
     </bar2>
   </bar1>
</foo>'''

root = ET.fromstring(xml)
ids = [f.attrib.get('id') for f in root.findall('.//foobar')]
print(ids)

output

['2','3']
Sign up to request clarification or add additional context in comments.

Comments

1

You need to specify a working XPATH expression, like:

foobars = source.findall('bar1/bar2/foobar')
for elem in foobars:
    print(elem.get('id'))

Output:

2
3

Comments

0

It works now for one line, but what if we have several bar1? Like this

<foo>
   <bar1 id="1">
      <bar2>
        <foobar id="2">name1</foobar>
        <foobar id="3">name2</foobar>
     </bar2>
   </bar1>
   <bar1 id="2">
      <bar2>
        <foobar id="2">name3</foobar>
        <foobar id="3">name4</foobar>
     </bar2>
   </bar1>
</foo>

The loop (findall=> for)will print all of it(4 ids), but i need just 2 of them for each row

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.