pythonxmlxml-namespacesminidom

Creating XML document with namespace


I am trying to generate an XML document using xml.dom.minidom.

What I need to get:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns3:loginResponse xmlns:ns2="url1" xmlns:ns3="url2"><ns3:return>abcxyz</ns3:return></ns3:loginResponse>

I have tried this:

import xml.dom.minidom

doc = xml.dom.minidom.Document()
element = doc.createElementNS('url', 'ns25:getSecurityEvents')
element.setAttribute("xmlns:ns25","url")
main = doc.createElement('Text')eNode('Some text here')
main.appendChild(doc.createTextNode('Some text here'))
element.appendChild(main)
doc.appendChild(element)
print(doc.toprettyxml())

But I am getting output like this:

<ns25:getSecurityEvents xmlns:ns25="http://ws.v1.service.resource.manager.product.arcsight.com//securityEventService/">
<Text>Some text here</Text>
</ns25:getSecurityEvents>

I need to achieve two things:

  1. Multiple namespace declarations in root node

  2. Child node should be like <ns25:Text>Some text</ns25:Text>


Solution

  • In minidom, namespaces are treated as if they were attributes. You can do it like this:

    import xml.dom.minidom
    
    doc = xml.dom.minidom.Document()
    
    doc_elem = doc.createElement('getSecurityEvents')
    doc_elem.setAttribute('xmlns', 'http://ws.v1.service.resource.manager.product.arcsight.com//securityEventService/')
    doc.appendChild(doc_elem)
    
    text = doc.createElement('Text')
    text.appendChild(doc.createTextNode('Some text here'))
    doc_elem.appendChild(text)
    
    print(doc.toprettyxml())
    

    which prints

    <getSecurityEvents xmlns="http://ws.v1.service.resource.manager.product.arcsight.com//securityEventService/">
        <Text>Some text here</Text>
    </getSecurityEvents>
    

    This is effectively what you want. If all the elements should be in the same namespace, you can make that the default namespace and drop the namespace prefixes. Here, <Text> is in the same namespace as <getSecurityEvents>.

    When you want to write it to file, use something like this (write in binary mode & explicit set encoding):

    with open('filename.xml', 'wb') as xml_file:
        xml_file.write(doc.toxml('utf-8')) 
    

    This makes sure the proper XML declaration is added and the file encoding is good.