Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
XML to table CSV
#1
Hi all,

I have an question about parsing a XML-file to a table in CSV. What script can I use to make the XML file into a CSV file with tables.

My XML file is like:
<xml version="1.0">
<Person>
<General>
<Date Value="22/1/2016" />
<Version Value="16.3.2.38" />
<Name Value="MyName" />
</General>
</Person>
<Person>
<General>
<Date Value="22/1/2016" />
<Version Value="16.3.2.38" />
<Name Value="MyName2" />
</General>
</Person>
</xml>

Till now I use the script:
import xml.etree.ElementTree as ET
import csv       

tree = ET.parse("mydir")
root = tree.getroot()

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

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

count = 0
for member in root.findall('Resident'):
	resident = []
	address_list = []
	if count == 0:
		DateValue = member.find('Date Value').tag
		resident_head.append(DateValue)
		VersionValue = member.find('Version Value').tag
		resident_head.append(VersionValue)
		NameValue = member.find('Name Value').tag
		resident_head.append(NameValue)

		csvwriter.writerow(resident_head)
		count = count + 1

	DateValue = member.find('Date Value').text
	resident.append(GameDateValue)
	VersionValue = member.find('Version Value').text
	resident.append(VersionValue)
	NameValue = member.find('Name Value').text
	resident.append(NameValue)

	csvwriter.writerow(resident)
Resident_data.close()
The error I receive is:
Error:
Traceback (most recent call last): File "testallfilesv2.py", line 40, in <module> tree = ET.parse("mydir") File "C:\Python27\lib\xml\etree\ElementTree.py", line 1182, in parse tree.parse(source, parser) File "C:\Python27\lib\xml\etree\ElementTree.py", line 656, in parse parser.feed(data) File "C:\Python27\lib\xml\etree\ElementTree.py", line 1653, in feed self._raiseerror(v) File "C:\Python27\lib\xml\etree\ElementTree.py", line 1517, in _raiseerror raise err ParseError: junk after document element: line 179, column 6
Reply
#2
Then xml parser cannot read the source. You need to look at line 179 in the file "mydir" to see what puzzles the parser.
Reply
#3
Thanks for your quick answer, on row 179 the first XML ends with </xml>.
On row 180 a new one starts with <xml version="1.0">
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020