XML edit attributes
I want to edit the attributes of an element in an XML file.
开发者_如何学CThe 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.
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>
精彩评论