2

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

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks that helped.. Could you please help me have the view changed such that tag is the header and we have the corresponding text under that.
2

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)

1 Comment

thanks that helped.. Could you please assist me on how I could have the tag added to a column and have the text under that..

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.