XML : Save (print) xml node with its parents but without children

From the XML document, I want to save one node to a file - with all parent nodes, but without any child nodes. For example, for the following XML:

  <?xml version="1.0" encoding="UTF-8"?>  <kml xmlns="http://earth.google.com/kml/2.1">   <Document id="myid">    <name>ref.kml</name>    <Style id="normalState">       <IconStyle><scale>1.0</scale><Icon><href>yt.png</href></Icon></IconStyle>        </Style>   </Document>  </kml>    

expected output for <Document> node will be like this:

  <?xml version="1.0" encoding="UTF-8"?>  <kml xmlns="http://earth.google.com/kml/2.1">   <Document id="myid">   </Document>  </kml>    

So far I only found a solution with iterated removal of all child elements before saving. But as I need to work with original XML after, I have to make a copy of the whole document:

  #!/usr/bin/env python    import lxml.etree as ET # have to use [lxml] because [xml] doesn't support 'xml_declaration'  import copy    kml_file = ET.parse("myfile.kml")  kml_copied = copy.deepcopy(kml_file) # .copy() is not enough, need .deepcopy()  root = kml_copied.getroot()  my_node = root[0]  for child in my_node:      my_node.remove(child)  print ET.tostring(kml_copied, xml_declaration=True, encoding='utf-8')    

Is there better way to do this? at least to avoid making a deepcopy of the whole document...

No comments:

Post a Comment