[Tutor] XML: changing value of elements

Johan Geldenhuys johan at accesstel.com.au
Thu Jun 11 22:40:56 CEST 2009


Thanks for the reply. Have been waiting a few days.

When I started out, I still had Python 2.4 and etree is not available in
that version.

This part : <file:///C:\Users\Public\XML%20parse\signal1.xml##>
must have snicked in wihen I copied the XML code. Sorry, but that is the
location of my original XML file.

I'll try your stuff and see how it goes.

Thanks
 
Johan 

-----Original Message-----
From: tutor-bounces+johan=accesstel.com.au at python.org
[mailto:tutor-bounces+johan=accesstel.com.au at python.org] On Behalf Of Stefan
Behnel
Sent: Thursday, 11 June 2009 16:37 PM
To: tutor at python.org
Subject: Re: [Tutor] XML: changing value of elements

Hi,

it's funny how many times I see Python users go: "I have an XML problem, so
I'll use minidom." Because then they have two problems.


Johan Geldenhuys wrote:
> I have a rather complex XML file and I need to change some values inside
> this file.
> 
> So far I have been using minidom, but I can't find the thing I am looking
> for.
> 
> My code so far:
> """
> from xml.dom import minidom
> 
> xmlFile = 'signal1.xml'
> xmlDocument = minidom.parse(xmlFile)
> 
> SignalsNode = xmlDocument.firstChild
> signalNode = SignalsNode.childNodes[1]
> 
> signalNode.removeAttribute("name")
> signalNode.setAttribute("name", "Test_Name")
> signalNode.getAttribute("name")
> 
> descElem = signalNode.childNodes[1]

That is a lot of code just to say

	import xml.etree.ElementTree as ET
	doc = ET.parse('signal1.xml')
	signal_node = doc.getroot()[0]
	signal_node.set('name', 'Test_Name')


> I know how to manipulate the value of the attributes, but I can't seem to
> change the values of eg: "Description"

	description = signal_node[0]
	description.text = "New value"

> Snippet from my XML file:
> 
> """
> 
> <?xml version="1.0" encoding="UTF-8" ?> 
> 
>  <file:///C:\Users\Public\XML%20parse\signal1.xml##> - <Signals> 

What's that "<file:///C:\Users\Public\XML%20parse\signal1.xml##>" bit?


>  <file:///C:\Users\Public\XML%20parse\signal1.xml##> - <Signal
model="Model"
> name="Model_X" type="Flyer">
> 
>   <Description>Some description</Description> 
> 
>   <SpecName> Model_X </SpecName> 
> 
>   <Reporting category="POW" name="" /> 
> 
>  <file:///C:\Users\Public\XML%20parse\signal1.xml##> - <Trigger
type="open">
> 
>   <Severity>normal</Severity> 
> 
>   <Message>Model X 1</Message> 
> 
>   </Trigger>
> 
>  <file:///C:\Users\Public\XML%20parse\signal1.xml##> - <Trigger
> type="close">
> 
>   <Severity>minor</Severity> 
> 
>   <Message> Model X 2</Message> 
> 
>   </Trigger>
> 
>   </Signal>
> 
>   </Signals>
> """

Stefan

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list