i have a small XML file which looks like this:
<cart>
<items>
<item id="1" />
</items>
<items>
<item id="2" />
</items>
</cart>
and I want to add a new item <item id = "new item" />
under both <items></items>
. This is my code:
doc = minidom.parseString('<cart><items><item id="1" /></items><items><item id="2" /></items></cart>')
newItem = doc.createElement('item')
newItem.setAttribute('id', 'new item')
items = doc.getElementsByTagName('item')
for item in items:
item.parentNode.appendChild(newItem)
print(item.parentNode.toxml())
print(doc.toprettyxml())
NOTE: I could have taken <items></items>
and used items.appendChild, but i need <item></item>
elements later. Thats why using parentNode.appendChild
Here's the output i am getting
<items><item id="1"/><item id="new item"/></items>
<items><item id="2"/><item id="new item"/></items>
<cart>
<items>
<item id="1" />
</items>
<items>
<item id="2" />
<item id="new item" />
</items>
</cart>
The first 2 lines are the output of the print statement inside the loop.
See, the new element doesn't get added under the first items block. However, the print statement inside the for loop shows that both the items blocks has got the new element added, but the Document node 'doc' is showing only the item under the second items block. Link to the code on Ideone
Any help on What am i doing wrong ?
You can't have the same element in multiple places. When you append to the second node, newItem is removed from the first node. You can copy the node instead:
doc = minidom.parseString('<cart><items><item id="1" /></items><items><item id="2" /></items></cart>')
newItem = doc.createElement('item')
newItem.setAttribute('id', 'new item')
items = doc.getElementsByTagName('item')
for item in items:
item.parentNode.appendChild(newItem.cloneNode(True))
print(item.parentNode.toxml())
print(doc.toprettyxml())