From my xml file, I want to write each child node to a separate file. I use xml.etree.ElementTree.tostring(child_node) for this. I already found that I should use .register_namespace() to avoid adding "ns0:" to every tag. But I still have "xmlns=" attribute added to every node I am saving:
Here is sample xml file:
<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://earth.google.com/kml/2.1"> <Document> <name>ref.kml</name> <Style id="normalState"> <IconStyle><scale>1.0</scale><Icon><href>yt.png</href></Icon></IconStyle> <BalloonStyle><text><![CDATA[$[description]]]></text></BalloonStyle> </Style> </Document> </kml> Here is my code:
#!/usr/bin/env python import xml.etree.ElementTree as ET str_ns_url = 'http://earth.google.com/kml/2.1' ET.register_namespace('', str_ns_url) kml_file = ET.parse('my.kml') kml_doc = kml_file.getroot()[0] ndx = 0 for child in kml_doc: ndx+=1 f = open('node'+str(ndx)+'.txt','w') f.write(ET.tostring(child)) f.close() And this is the output for the first node (<name>):
<name xmlns="http://earth.google.com/kml/2.1">ref.kml</name> As you see, xmlns= was added to the tag. So far I only found this SO post which basically suggests manual removal of that substring after .tostring(). Is there any better solution? Maybe I should use something else instead of ElementTree.tostring()?
No comments:
Post a Comment