Monday, August 20, 2018

Same prefix, multiple namespace in XML - How to add element attrib without affecting other in Python

I have the below input XML:



    
        
            
            
            
        
    


As you can see, xmlns is used for two namespaces , "urn:jboss:domain:4.1" and "urn:jboss:domain:jmx:1.3"

I would like to add an attribute to host element

Below is my code in Python:

from xml.etree import ElementTree as ET

def parse_xml():
    ET.register_namespace('','urn:jboss:domain:4.1')
    tree = ET.parse('sample.xml')
    root = tree.getroot()
        for elements in tree.iter():
        if "host" in elements.tag :
            elements.attrib['name'] = "slaveOne"
            print elements.attrib
            tree.write('sample.xml')

The above code changes the XML as below:



    
        
            
            
            
        
    


tree.write('sample.xml')

Changes all elements belonging to same prefix in this case

ET.register_namespace('','urn:jboss:domain:4.1')

  • How do i isolate the changes only to host element

Solved

You can try using minidom:

from xml.dom import minidom

doc = minidom.parse("sample.xml")

#getElementsByTagName returns NodeList
#grab first
host = doc.getElementsByTagName("host")[0]

#set attr -> value
#look at setAttributeNS in minidom docs for namespaces 
host.setAttribute('name', '123')

#write to file
with open('sample2.xml', 'w') as xmlfile:
    doc.writexml(xmlfile)

Take a look at xml.sax package and this XML Processing Modules page too.


No comments:

Post a Comment