replacing string in xml file--revisited

saif.shakeel at gmail.com saif.shakeel at gmail.com
Thu May 10 04:55:30 EDT 2007


On May 10, 1:42 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
>
> try this...
>
> #!/usr/bin/env python
>
> from elementtree import ElementTree as et
> tree = et.parse("testxml.xml")
>
> for t in tree.getiterator("SERVICEPARAMETER"):
>         t.set("Semantics", "localId")
>
> tree.write("output.xml")
>
> ~Sean- Hide quoted text -
>
> - Show quoted text -

           #!/usr/bin/env python


from elementtree import ElementTree as et
tree = et.parse("testxml.xml")


for t in tree.getiterator("SERVICEPARAMETER"):
        t.set("Semantics", "localId")


tree.write("output.xml")
                                             Is this code
complete,where are you replacing the localid with "datapackageid",and
where is the new xml being stored.
                                Thanks for the replies




More information about the Python-list mailing list