Grigor Aleksanyan
Grigor Aleksanyan

Reputation: 550

Python. How to get all element from xml file with concrete tag?

I use lxml.etree.

For example I have the xml file like this:

<Company>
  <Employee>
      <FirstName>Tanmay</FirstName>
      <LastName>Patil</LastName>
      <Valod>
          <Person Name="Jack"></Person>
      </Valod>
      <ContactNo>1234567890</ContactNo>
      <Email>[email protected]</Email>
      <Address>
           <City>Bangalore</City>
           <State>Karnataka</State>
           <Zip>560212</Zip>
           <Room>
               <Person Name="Bill"></Person>
               <Person Name="John"></Person>
           </Room>
      </Address>
  </Employee>
</Company>

As a result of search I want all 'persons'. Something like 'element.getAll('person')' which returns elements:

<Person Name="Jack"></Person>
<Person Name="Bill"></Person>
<Person Name="John"></Person>

Upvotes: 0

Views: 2399

Answers (2)

G T
G T

Reputation: 66

Check this tutorial from the official Python site which shows exactly what you need.

import xml.etree.ElementTree as ET
tree = ET.parse('person.xml')
root = tree.getroot()
for person in root.findall('Person'):
    do something

Upvotes: 4

Rach Sharp
Rach Sharp

Reputation: 2434

You can use XPaths

https://docs.python.org/2/library/xml.etree.elementtree.html#elementtree-xpath

It will probably be something like root.findall("//Person") where root is an ElementTree, since // is find all children, immediate or otherwise, and Person is the node name.

Upvotes: 2

Related Questions