replacing string in xml file--revisited
half.italian at gmail.com
half.italian at gmail.com
Thu May 10 04:55:10 EDT 2007
On May 10, 12:56 am, saif.shak... at gmail.com wrote:
> Hi,
> I need to replace a string in xml file with something else.Ex
>
> - <SERVICEPARAMETER id="_775" Semantics="subfunction" DDORef="_54">
> <SHORTNAME>rate</SHORTNAME>
> <LONGNAME>rate</LONGNAME>
> <VALUE role="constant" DataType="unsigned" value="1" />
> <BYTEPOSITION role="position" BytePos="1" />
> </SERVICEPARAMETER>
> - <SERVICEPARAMETER id="_776" Semantics="localId" DDORef="_54">
>
> Here i have opened an xml
> file(small part is pasted here).I want to replace the word 'localId'
> with 'dataPackageID' wherever it comes in xml file.I have asked this
> before and got a code:
> input_file = open(filename)
> xmlcontents = input_file.read()
> input_file.close()
> xmlcontents = xmlcontents.replace("spam", "eggs")
> output_file = open(filename,"w")
> output_file.write(xmlcontents)
> output_file.close()
>
> Although this works alone it is nto
> working when i handle multiple file I/O.Is there a alternative to do
> this.(maybe without read() operation)
> Thanks
After reading your post again, this might be better:
#!/usr/bin/env python
from elementtree import ElementTree as et
tree = et.parse("testxml.xml")
for t in tree.getiterator("SERVICEPARAMETER"):
if t.get("Semantics") == "localId":
t.set("Semantics", "dataPackageID")
tree.write("output.xml")
~Sean
More information about the Python-list
mailing list