Miek
Miek

Reputation: 1137

Python edit xml with minidom

Try as I might I just not getting this to work. I have an xml file:

: enter image description here

I need to change the values of xyz and add a name to the name tag. I just can't seem to figure out how to get there.

my code:

#!/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()

I have tried several variations of sensor.childNodes[0].data or value. This returns error for no attribute. If I use print sensor.toxml() everything is as it should be.

when I run this code I do get the test to print , but its inserted right after the "sensor" tag and not the "name" tag. Simple syntax issue I know, but I'm just not finding it in the docs.

Very appreciative for the help.

Upvotes: 1

Views: 941

Answers (1)

Miek
Miek

Reputation: 1137

I could not find a solution with minidom.

I switched to ElementTree and was able to trip over a solution. What I actually needed to do was read in a .csv file and rewrite the xml with the values from the second file, but that turned out to be trivial compared to getting the xml overwritten.

solution from previous:

#!/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()

Notice the top line of the xml boiler plate needs to be replaced manually. Also you either need to create a custom method to clean prefix name spaces <ns0: tagname > or remove the schema before processing and replace, depending on what your needs are. some people want the prefixes.

Upvotes: 2

Related Questions