[Tutor] Search and replace text in XML file?

Alan Gauld alan.gauld at btinternet.com
Sat Jul 28 10:45:24 CEST 2012


On 28/07/12 02:38, Todd Tabern wrote:
> I'm looking to search an entire XML file for specific text and replace that text,
 > while maintaining the structure of the XML file.

Do you mean the physical layout of the file or the technical XML 
structure? I'm assuming its the latter? If it's the former just
use 'tidy' to reformat the file.

> I basically need to replace every occurrence C:\Program Files with C:\Program Files (x86),
 > regardless of location. ...
> I've tried some non-python methods and they all ruined the XML structure.

Can you give examples of what you tried? I'd have gone for sed for a job 
like this.

 > I've been Google searching all day and can only seem
> to find solutionsthat look for a specific node
 > and replace the whole string between the tags.

Because that's usually the requirement, but generally
you can extract the existing string and do the substitution
and then write back the new version.

> I've been looking at using minidom to achieve this

I'd consider element tree if you must do it via a parser, but it sounds 
like you don't need that, sed or simple string replacements should 
suffice here.

> compile an exe that can work on machines without python,

You can do that with Python but its not my favourite approach, you'd be 
better with a sed based solution. (You can get GNU sed for Windowss and 
it already is installed on MacOS/Linux boxes.)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list