Python用minidom编辑xml

时间:2015-02-13 15:25:15

标签: python xml-parsing

尽可能地尝试我不能让它发挥作用。我有一个xml文件:

:     enter image description here

我需要更改xyz的值并为name标签添加名称。我似乎无法弄清楚如何到达那里。

我的代码:

#!/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的几种变体。这将返回no属性的错误。如果我使用print sensor.toxml(),一切都应该如此。

当我运行这段代码时,我确实得到了要打印的测试,但它是在"传感器"之后插入的。标签,而不是"名称"标签。我知道简单的语法问题,但我只是在文档中找不到它。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

我找不到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()

请注意,需要手动更换xml样板的顶行。 您还需要创建一个自定义方法来清除前缀名称空间&lt; ns0:tagname&gt;或者在处理和替换之前删除架构,具体取决于您的需求。有些人想要前缀。