Reputation: 5492
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>
Upvotes: 0
Views: 1553
Reputation: 1121744
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.
Upvotes: 3