david
david

Reputation: 6785

How to to search a key in an xml and replace it's value with Python?

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.

Upvotes: 1

Views: 93

Answers (2)

John Gordon
John Gordon

Reputation: 33275

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

Upvotes: 0

Rafael T
Rafael T

Reputation: 15679

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)

Upvotes: 2

Related Questions