Taking data from an XML document and writing it to another XML document with python



I've been trying for a while now to do this.


Basically, i have an XML document in the following format(which contains the information i need - the ID and coordinates of some points):



<root>
<!-- Title element missing here -->
<Table>
<Point>
<ID>Point1</ID>
<latitude>numbers</latitude>
<longitude>numbers</longitude>
</Point>
</Table> <!-- This line should be eliminated -->
<Table> <!-- This line should be eliminated -->
<Point>
<ID>Point2</ID>
<latitude>numbers</latitude>
<longitude>numbers</longitude>
</Point>
</Table>
</root>


What i need to do is to take this document and output it in a different format (like i displayed above, in the original XML file), without changing the original XML file.


I wrote the following code for the above task, but i hit a brick wall, so to speak. I am also rather new to python as well.



from lxml import etree
import xml.etree.ElementTree as ET
doc=etree.parse('test2.xml')
root=doc.getroot()
elements=root.findall(".//Point")

root=ET.Element('root')
title=ET.SubElement(root,'Title')
title.text="Title"
table=ET.SubElement(root,'Table')
for element in elements:
point=ET.SubElement(table,'Point')
elem=ET.SubElement(point,'ID')
elem.text="Name"
elem2=ET.SubElement(point,'latitude')
elem2.text="coords"
elem3=ET.SubElement(point,'longitude')
elem3.text="coords"
ET.dump(root) # using ET.dump just to display the output in the python SHELL


The code above gives me the following output in SHELL, which is what i need.



<root>
<Title>Title</Title>
<Table>
<Point>
<ID>Name</ID>
<latitude>coords</latitude>
<longitude>coords</longitude>
</Point>
<Point>
<ID>Name</ID>
<latitude>coords</latitude>
<longitude>coords</longitude>
</Point>
</Table>
</root>


My problem comes when i have to take the values of ID,latitude and longitude from the original XML file and writing the whole new document in a new XML file, with pretty_print as well, for easier reading. I simply can't fingure it out. Some tips would be greatly appreciated.


No comments:

Post a Comment