0

I'm trying to replace a string in an xml file with python. For example:

I want to change enabled to disbabled in:

<s:global-method-security secured-annotations="enabled"/>

Is it best to search and replace the whole line? Or is there a way to just replaced the enabled on the line if I find a line that matches?

2 Answers 2

3

A simple way could be:

for line in fileh:
    line = line.replace("enabled", "disabled")
    ouf.write(line)

You do not need to explicitly find "enabled" in the string before replacing it.

However, since its an xml file, I would suggest using the xml parser to modify it.

Sign up to request clarification or add additional context in comments.

2 Comments

This looks like it should work, but what is ouf.write exactly? I can't find anything on it, typo?
Outf is a file handle for a temporary file. Once you are done with the replace process, you delete the old file and rename the temporary file.
1

Just use string.replace():

for line in whateverXMLText.splitlines(): # or whatever arbitrary loop
    if line.find("enabled") > -1:
        print "Replacing 'enabled' on line: %s" % line
        line.replace("enabled", "disabled")

A better solution though, may be to use an xml parser (xml.dom.minidom), and change the attribute during parsing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.