0

I want to add a Subelement to a XML file without writing the content to the console.

I am doing the following to add a subelement to a XML file:

import xml.etree.ElementTree as ET
tree=ET.parse('myfile.XML')
root=tree.getroot()
vpn=ET.SubElement(root,'VPN', attrib={'A': 'VPN1', 'B':'0','C': '0.0001', 'D': '0', 'E': '%'})
ET.dump(root)

This does what it should do. But ET.dump()is writing the XML content to the console which is problematic for bigger XML structures.

In any case the documentation is a bit weird here. Because on the one hand the documentation (see chapter "Building XML documents") says that dump() should be used to add a sub-element. On the other hand the documentation of the dump() method indicates that this method should only be used for debugging, which explains why content is printed out to the console.

How can I add a XML Subelement without having the content in the console?

VKlue
  • 21
  • 4
  • 1
    If you don't want to print the xml to the console, then ... don't call `dump()`. What is the actual problem here? – John Gordon Mar 06 '23 at 01:39
  • 1
    If you want to write it to a file instead of display to console, use `root.write('myfile.xml')` instead – dinhit Mar 06 '23 at 01:43
  • @dinhit I need to add many subelements. So I cannot write to the file and read again the file all the time. – VKlue Mar 06 '23 at 06:15
  • So use call it when you are done, what is the purpose of `dump()`? – dinhit Mar 06 '23 at 06:58

2 Answers2

1

Thanks for all your input. The simple answer is that neither dump() not append() needs to be called. When writing the file all the Subelements added by the SubElement method will be included. I got confused due to the documentation example and the fact that you cannot access the added SubElements by the get() method.

VKlue
  • 21
  • 4
0

You can use root.append(vpn) instead of ET.dump(root) this won't write to the console. 

import xml.etree.ElementTree as ET
tree=ET.parse('myfile.XML')
root=tree.getroot()
vpn=ET.SubElement(root,'VPN', attrib={'A': 'VPN1', 'B':'0','C': '0.0001', 'D': '0', 'E': '%'})
# ET.dump(root)
root.append(vpn)
#To dump the data into a file:    
tree = ET.ElementTree(root)
tree.write('xml_filename.xml')