使用python在现有的xml文档中插入xml节点 [英] Inserting xml nodes in an existing xml document with python

查看:70
本文介绍了使用python在现有的xml文档中插入xml节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在此文档中插入 xml 节点:

I am trying to insert xml nodes in this document:

</providers>

</root>

我写了这段代码:将 xml.dom.minidom 导入为 m

I wrote this code: import xml.dom.minidom as m

doc = m.parse("monfichier.xml")
valeurs = doc.getElementsByTagName("providers")
element = doc.createElement("provider")
valeurs.appendChild(element)

elthost = doc.createElement("hostnamep") 
eltLTVC = doc.createElement("LocalTrustValueC")
element.appendchild(elthost)
element.appendchild(eltLTVC)

texteHost = doc.createTextNode("machinename")
texteLTVC = doc.createTextNode("23") 
eltHost.appendChild(texteHost)
eltLTVC.appendChild(texteLTVC)
doc.writexml(open("monfichier.xml","w"))

我想在最后获得这个 xml 文件:机器名23

And I want to obtain at the end this xml document : machinename 23

    </provider> 
</providers>

</root>

但是我得到了这个错误:valeurs.appendChild(元素)AttributeError: 'NodeList' 对象没有属性 'appendChild'

But I obtained this error : valeurs.appendChild(element) AttributeError: 'NodeList' object has no attribute 'appendChild'

推荐答案

基于对http://docs.python.org/library/xml.dom.html#dom-node-objects 看来 NodeList 没有 appendChild 方法.相反,您想获取结果集中的第一个节点(因为您的帖子暗示只有一个)并在该节点上调用 appendChild.

Based on some quick reading of http://docs.python.org/library/xml.dom.html#dom-node-objects it appears that NodeList does not have an appendChild method. Instead you want to get the first Node in the result set(since your post implies there is only one) and call appendChild on that node.

valeurs = doc.getElementsByTagName("providers").item(0)
element = doc.createElement("provider")
valeurs.appendChild(element)

这篇关于使用python在现有的xml文档中插入xml节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆