Python使用minidom编辑xml

Python使用minidom编辑xml,python,xml-parsing,Python,Xml Parsing,尽我所能,我只是没能让它发挥作用。我有一个xml文件: : 我需要更改xyz的值,并在名称标记中添加一个名称。我只是不知道怎么去那里 我的代码: #!/usr/bin/env python # -*- coding: utf-8 -*- from xml.dom import minidom xmldoc = minidom.parse('example.xml') sensorList = xmldoc.getElementsByTagName('sensor') for senso

尽我所能,我只是没能让它发挥作用。我有一个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]的几种变体。数据或值。这将返回无属性的错误。如果我使用print sensor.toxml(),一切都会正常

当我运行这段代码时,我确实会打印测试,但是它会直接插入到“sensor”标记后面,而不是“name”标记后面。简单的语法问题我知道,但我只是在文档中找不到它


非常感谢您的帮助。

我找不到使用minidom的解决方案

我切换到ElementTree,并能够在解决方案上绊倒。 我实际上需要做的是读取一个.csv文件并用第二个文件中的值重写xml,但这与重写xml相比是微不足道的

以前的解决方案:

#!/usr/bin/python

import sys
import xml.etree.ElementTree as ET
xmlFile = sys.argv[1]

# Xml parsing.
tree = ET.parse(xmlFile)
root = tree.getroot()

#Access the nodes you want by treating root as an array of arrays
# roots children = root[x]
# roots children's children root[x][y]etc

#The array of sensors
sensors = root[1]

for sensor in sensors:
#Access all of sensors children the same way as root.
    sensor[0].text = 'test'
    sensor[3].text = '1'
    sensor[4].text = '2'
    sensor[5].text = '3'

#Open the xmlfile and rewrite it.
xmlFileHandle = open(xmlFile,'wb')
xmlFileHandle.write('<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(root))
xmlFileHandle.close()
#/usr/bin/python
导入系统
将xml.etree.ElementTree作为ET导入
xmlFile=sys.argv[1]
#Xml解析。
tree=ET.parse(xmlFile)
root=tree.getroot()
#通过将根视为数组来访问所需的节点
#根子项=根[x]
#根儿童的根[x][y]等
#传感器阵列
传感器=根[1]
对于传感器中的传感器:
#以与root相同的方式访问所有传感器子项。
传感器[0]。文本=“测试”
传感器[3]。文本='1'
传感器[4]。文本='2'
传感器[5]。文本='3'
#打开XML文件并重写它。
xmlFileHandle=open(xmlFile,'wb')
xmlFileHandle.write('\n'+ET.tostring(根))
xmlFileHandle.close()
请注意,xml锅炉板的顶行需要手动更换。 此外,您还需要创建一个自定义方法来清除前缀名称空间,或者在处理和替换之前删除架构,具体取决于您的需要。有些人想要前缀