[英]How to to search a key in an xml and replace it's value with Python?
我在xml文件中有数千个这些应用程序名称行:
<app name="app-sq-461-author-core-0">
我要执行以下操作:
目前,我有:
bare = importedxml.find('app name')
testvalue = bare.split("=")[1]
if testvalue = "test" in importedxml:
testvalue = "delete me"
做这个的最好方式是什么? 我遇到很多问题。
您尝试过BeautifulSoup吗? 这些东西
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))
但是,正如您在下面的评论中提到的那样,您没有bs4,我唯一想到的就是使用正则表达式替换。
import re
xml = "your XML String"
pattern = re.compile('app name="test"')
replaced = pattern.sub('app name="delete me"', xml)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.