1

I have thousands of these app name lines in an xml file:

<app name="app-sq-461-author-core-0">

I want to do the following:

  1. check through all lines that 'app name' exists
  2. if so, see if the value matches "test"
  3. If so, replace the value with "delete me"

Currently, I have:

bare = importedxml.find('app name')
testvalue = bare.split("=")[1]
if testvalue = "test" in importedxml:
   testvalue = "delete me"

What is the best way to do this? I'm encountering many problems.

2 Answers 2

2

Have You tried BeautifulSoup? Something along these lines

import bs4

xml = "Your bare XML String"
soup = bs4.BeautifulSoup(xml)
test_apps = soup.findChildren("app", {"name": "test"})
for app in test_apps:
    app["name"] = "delete me"

with open("filename.xml", "w") as f:
    f.write(str(soup))

but, as you mentioned in you comment below, that you do not have bs4, the only thing I can think of is using a regex replace.

import re

xml = "your XML String"
pattern = re.compile('app name="test"')
replaced = pattern.sub('app name="delete me"', xml)
Sign up to request clarification or add additional context in comments.

1 Comment

Yea I really want to switch over to beautiful soup, the problem is getting my work place to approve. So for now, I can't use it.
0
sed 's/<app name="foo">/<app name="bar">/g' < file.xml > file.xml.new
mv file.xml file.xml.old
mv file.xml.new file.xml

2 Comments

How do you know, that op has a *nix machine?
I don't. The command syntax ought to be similar enough, no? And even if op's machine does not have sed at all, the intent of the operation is clear.

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.