Reputation: 550
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
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
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