使用xml.dom.minidom(appendChild)在特定位置添加subElement

时间:2017-02-24 07:58:42

标签: python xml xml-parsing

我打算在指定位置插入一个子元素。但是,我不知道如何使用 xml.dom 中的 appendChild 来做到这一点 这是我的xml代码:

<?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>

我想在“cd”标签之前的第一个“root”元素中插入另一个子元素“new”。结果应如下所示:

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

我用的代码是:

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"))

我能以什么方式实现目标?

提前谢谢.. !!

0 个答案:

没有答案