replacing string in xml file--revisited

half.italian at gmail.com half.italian at gmail.com
Thu May 10 12:44:01 EDT 2007


On May 10, 4:21 am, saif.shak... at gmail.com wrote:
> On May 10, 1:55 pm, half.ital... at gmail.com wrote:
>
>
>
> > 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- Hide quoted text -
>
> > - Show quoted text -
>
>  which module should be imported for above to work,it says
>  ImportError: No module named elementtree
>              Thanks

You can either 1) upgrade to python 2.5 which includes the elementtree
module or 2) download and add the module to your current installation

http://effbot.org/zone/element-index.htm

~Sean




More information about the Python-list mailing list