Thursday, January 18, 2018

Python script to parse attribute names of XML file

------------------------------------------------------------------------------------

import xml.etree.ElementTree as ET
import csv

tree = ET.parse("ResidentData.xml")
root = tree.getroot()

# open a file for writing

Resident_data = open('/tmp/ResidentData.csv', 'w')

# create the csv writer object

csvwriter = csv.writer(Resident_data)
resident_head = []

count = 0
for member in root.findall('Resident'):
resident = []

name = member.get('name_value')
resident.append(name)
csvwriter.writerow(resident)

Resident_data.close()




______________________________________________________________________________________
XML
_________________________________________________________________

<State>
<Resident Id="100">
<Name name_value="Name123">Sample Name</Name>
<PhoneNumber name_value="Phone123">1234567891</PhoneNumber>
<EmailAddress name_value="Email123">sample_name@example.com</EmailAddress>

</Resident>
<Resident Id="101">
<Name name_value="12name1234">Sample Name1</Name>
<PhoneNumber name_value="12Phone1234">1234567891</PhoneNumber>
<EmailAddress name_value="12Email1234">sample_name1@example.com</EmailAddress>

</Resident>
</State>



________________________________________________________________________________
Sample Output
________________________________________________________________________________

Name123
12name1234



Reference:

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

http://blog.appliedinformaticsinc.com/how-to-parse-and-convert-xml-to-csv-using-python/

No comments: