Linked Questions

Popular Questions

Python: specify XMLNS on xml.etree elements

Asked by At

in my Python code I'm currently using the xml.etree library to create a tree and then dump it to an XML string. Unfortunately I can't use modules other than the ones in the Python Standard Libraries to do that.

Here is my code:

import xml.etree.ElementTree as ET

def dump_to_XML():
  root_node = ET.Element("root")
  c1_node = ET.SubElement(root_node, "child1")
  c1_node.text = "foo"
  c2_node = ET.SubElement(root_node, "child2")
  gc1_node = ET.SubElement(c2_node, "grandchild1")
  gc1_node.text = "bar"
  return ET.tostring(root_node, encoding='utf8', method='xml')

which gives the string:

<?xml version='1.0' encoding='utf8'?>

Now, I have two schema files located - say - and, I want the output string to be turned into:

<?xml version='1.0' encoding='UTF-8'?>
<root xmlns:p="" xmlns:q="">

How can I leverage the etree library in order to achieve that?

Thanks in advance

Related Questions