【发布时间】:2015-04-14 16:33:28
【问题描述】:
尽我所能,我只是没有让这个工作。我有一个 xml 文件:
:
我需要更改 xyz 的值并将名称添加到名称标签。我就是不知道怎么去那里。
我的代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from xml.dom import minidom
xmldoc = minidom.parse('example.xml')
sensorList = xmldoc.getElementsByTagName('sensor')
for sensor in sensorList:
sensor.firstChild.nodeValue = "test"
sensor.nextSibling.nodeValue # skip over
sensor.nextSibling.nodeValue = "1"
sensor.nextSibling.nodeValue = "2"
sensor.nextSibling.nodeValue = "3"
#print sensor.toxml()
xml_file_handle = open('example.xml' , 'wb')
xmldoc.writexml(xml_file_handle)
xml_file_handle.close()
我已经尝试了 sensor.childNodes[0].data 或 value 的几种变体。这将返回没有属性的错误。如果我使用 print sensor.toxml() 一切正常。
当我运行此代码时,我确实得到了要打印的测试,但它是在“传感器”标签之后插入的,而不是“名称”标签之后。我知道简单的语法问题,但我只是在文档中找不到它。
非常感谢您的帮助。
【问题讨论】:
标签: python xml-parsing