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>
You create new DOM elements with the
Document.createElement()method, new DOM attributes can be added with theElement.setAttribute()method:You then have to create a text node and add that as a child to the
newdataElement, using theDocument.createTextNode()andNode.appendChild()methods:Now you can add the new element to your document root:
In other words, use the Python implementation of the DOM API.