pythonxmlelementtree

change namespace with XML.element.tree


Working with python :
My program opens a template in XML format, insert the user info, and then saves it.

The template is the following :

<ids xmlns="http://standards.buildingsmart.org/IDS" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://standards.buildingsmart.org/IDS http://standards.buildingsmart.org/IDS/1.0/ids.xsd">
    <info>
        <title></title>
        <version></version>
        <author></author>
        <date></date>
    </info>
    <specifications>
    </specifications>
</ids>  

I use xml.etree.ElementTree (and insert user data in this phase, which I skip for simplicity reasons) :

base_tree = ET.parse('XML_templates/base_structure_02.XML')
base_root = base_tree.getroot()

ET.indent(base_root,space ="    ")
xml_str = ET.tostring(base_root, encoding='unicode', method='xml')
print(xml_str)

And the output is :

<ns0:ids xmlns:ns0="http://standards.buildingsmart.org/IDS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://standards.buildingsmart.org/IDS http://standards.buildingsmart.org/IDS/1.0/ids.xsd">
    <ns0:info>
        <ns0:title />
        <ns0:version />
        <ns0:author />
        <ns0:date />
    </ns0:info>
    <ns0:specifications>
    </ns0:specifications>
</ns0:ids>

The thing is that I don't want the program to get a namespace to every item (ns0), is this possible ? thank you


Solution

  • The prefix ns0 stay for a missing namespace registration! You have to register_namespace():

    E.g.

    ET.register_namespace("", "http://standards.buildingsmart.org/IDS")
    

    PS: For some special requirements about namespaces, I reference also to the modul lxml.