Search code examples
pythonxmlminidom

Adding an attibute and value to an xml using xml.dom.minidom python


How can I add an attribut and value to an XML document using xml.dom.minidom in Python.

My XML is as follows

<?xml version="1.0" encoding="utf-8"?>

<PackageInfo xmlns="http://someurlpackage">


<data ID="http://someurldata1">data1</data >
<data ID="http://someurldata2">data2</data >
<data ID="http://someurldata3">data3</data >
</PackageInfo>

I want to add a new 'data' tag and it's id as 'http://someurldata4' and value as data4. So that the resulting xml will be as below. Sorry I don't want to use xml.etree.ElementTree

<?xml version="1.0" encoding="utf-8"?>

<PackageInfo xmlns="http://someurlpackage">
<data ID="http://someurldata1">data1</data >
<data ID="http://someurldata2">data2</data >
<data ID="http://someurldata3">data3</data >
<data ID="http://someurldata4">data4</data >
</PackageInfo>

Solution

  • You create new DOM elements with the Document.createElement() method, new DOM attributes can be added with the Element.setAttribute() method:

    newdata = doc.createElement(u'data')
    newdata.setAttribute(u'ID', u'http://someurldata4')
    

    You then have to create a text node and add that as a child to the newdata Element, using the Document.createTextNode() and Node.appendChild() methods:

    newdata.appendChild(doc.createTextNode(u'data4'))
    

    Now you can add the new element to your document root:

    doc.documentElement.appendChild(newdata)
    

    In other words, use the Python implementation of the DOM API.