Prashu Pratik
Prashu Pratik

Reputation: 51

Adding subElement at a specific location with xml.dom.minidom (appendChild)

I intend to insert a sub element at a specified location. However, I do not know how to do that using appendChild in xml.dom Here is my xml code:

<?xml version='1.0' encoding='UTF-8'?>

<VOD>
  <root>
	<ab>sdsd
		<pp>pras</pp>
		<ps>sinha</ps>
	</ab>
	<ab>prashu</ab>
	<ab>sakshi</ab>
	<cd>dfdf</cd>
  </root>
  <root>
	<ab>pratik</ab>
  </root>
  <root>
	<ab>Mum</ab>
  </root>
</VOD>

I would like to insert another sub element "new" in first "root" element just before the "cd" tag. The result should look like this:

<ab>prashu</ab>
<ab>sakshi</ab>
<new>Anydata</new>
<cd>dfdf</cd>

The code I used for this is:

import xml.dom.minidom as m

doc = m.parse("file_notes.xml")
root=doc.getElementsByTagName("root")

valeurs = doc.getElementsByTagName("root")[0]
element = doc.createElement("new")
element.appendChild(doc.createTextNode("Anydata"))
valeurs.appendChild(element)

doc.writexml(open("newxmlfile.xml","w"))

In what way can I achieve my goal?

Thank you in advance..!!

Upvotes: 0

Views: 3410

Answers (1)

Garett
Garett

Reputation: 16828

Try using insertBefore instead. Something along these lines:

element = doc.createElement("new")
element.appendChild(doc.createTextNode("Anydata"))
cd = doc.getElementsByTagName("cd")[0]
cd.parentNode.insertBefore(element, cd)

To insert new nodes based on an index you can just do:

 cd_list = doc.getElementsByTagName("cd")
 cd_list[0].parentNode.insertBefore(element, cd_list[0])

Upvotes: 2

Related Questions