I'm appending a node to an xml, but i want it to insert before some tags, could that be possible?
newNode = xmldoc.createElement("tag2")
txt = xmldoc.createTextNode("value2")
newNode.appendChild(txt)
n.appendChild(newNode)
This is my XML. When I append the child, it add after UniMed, I want it to insert after Cantidad and before UniMed. (Simplified version of my XML) "Item" can have more childs, and i do not know how many.
<ns0:Item>
<ns0:Cantidad>1</ns0:Cantidad>
<ns0:UniMed>L</ns0:UniMed>
</ns0:Item>
I think i can solve it by reading al the childs of Item, erase them, and then add them in the order I want. But i dont think its the best idea...
Any ideas?
EDITED
SOLUTION
itemChildNodes = n.childNodes
n.insertBefore(newNode, itemChildNodes[itemChildNodes.length-2])
Use insertBefore method to insert New created tag.
Demo:
>>> from xml.dom import minidom
>>> content = """
... <xml>
... <Item>
... <Cantidad>1</Cantidad>
... <UniMed>L</UniMed>
... </Item>
... </xml>
... """
>>> root = minidom.parseString(content)
>>> insert_tag = root.createElement("tag2")
>>> htext = root.createTextNode('test')
>>> insert_tag.appendChild(htext)
<DOM Text node "'test'">
>>>
>>> items = root.getElementsByTagName("Item")
>>> item = items[0]
>>> item_chidren = item.childNodes
>>> item.insertBefore(insert_tag, item_chidren[2])
<DOM Element: tag2 at 0xb700da8c>
>>> root.toxml()
u'<?xml version="1.0" ?><xml>\n\t<Item>\n\t <Cantidad>1</Cantidad><tag2>test</tag2>\n\t <UniMed>L</UniMed>\n\t</Item>\n</xml>'
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With