tags:

views:

49

answers:

1

Hi, I want to edit the attributes of an element in an XML file.

The file looks like

<Parameter name="Spec 2 Circumference/Length" type="real" mode="both">
    <Value>0.0</Value> 
    <Result>0.0</Result> 
</Parameter>

I want to replace the value and Result attribute with some other value from a text file.

Please suggest. Thanks in advance.

+1  A: 

An example using ElementTree. It will replace the Value elements text with some string; the procedure for the Result element is analogue and omitted here:

#!/usr/bin/env python

xml = """
<Parameter name="Spec 2 Circumference/Length" type="real" mode="both">
    <Value>0.0</Value> 
    <Result>0.0</Result> 
</Parameter>
"""

from elementtree.ElementTree import fromstring, tostring

# read XML, here we read it from a String
doc = fromstring(xml)

for e in doc.findall('Value'):
    e.text = 'insert your string from your textfile here!'

print tostring(doc)

# will result in:
#
# <Parameter mode="both" name="Spec 2 Circumference/Length" type="real">
#     <Value>insert your string from your textfile here!</Value> 
#     <Result>0.0</Result> 
# </Parameter>
The MYYN
Thanks a lot for the suggestion.Actually in real case I have an XML file containing these kind elements repetitively.I want to read the lines from that XMl file and do the thing as you said.Please give some hint on it .Thanks for your immediate reply.
manoj1123
please modify your question (above) instead of asking new questions in comments .. it more comprehensable that way; also, please always include relevant parts of code/data in your question and maybe some hints on where you stuck and why (errors, exceptions, ...) - last note: more people (rep-hunters) would answer this question, if it weren't a 'community wiki'
The MYYN
and welcome on SO ;)
The MYYN