dark horse
dark horse

Reputation: 447

Fetch data from xml using ElementTree in Python

I am trying to extract some data from a xml file. Given below is how the xml looks.

<?xml version="1.0" encoding="UTF-8"?>
<Stores>
  <Store>
<Action>new</Action>
<StoreID>1001</StoreID>
<EmpID/>
<Agent>
  <Name/>
  <EmpName>Scott</EmpName>
</Name>
<BillData>
  <BillInfo>
    <Action>new</Action>
    <CustName></CustName>
    <BillNumber>3343</BillNumber>
   </BillInfo>
  </BillData>
 </Store>
</Stores>

I am trying to fetch each of the columns along with its data from the above dataset. Given below is what I have achieved thus far:

import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
    for elem in root:
        for subelem in elem:
        print(subelem.tag)
        print(subelem.text)

Output is as below:

Action
new
StoreID
1001
Agent


BillData

I am trying to extract data that is at the child level. Could anyone advice how could I extract data stored under 'BillInfo' namely

Action
new
CustName
BillNumber
3343

Upvotes: 2

Views: 805

Answers (2)

TheWildHealer
TheWildHealer

Reputation: 1626

Simple recursive function that achieves what you want :

import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
search(root)

def search(elem):
    for e in elem:
        print(e.tag)
        print(e.text)
        search(e)

Upvotes: 2

loganasherjones
loganasherjones

Reputation: 1060

If you want to recursively iterate over all elements in the XML tree, you should use the iter method. Something like the following should get you want you want:

import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
for elem in tree.iter():
    print(elem.tag)
    print(elem.text)

Upvotes: 2

Related Questions