2016-03-07 85 views
1

我有數以千計的應用程序名稱的行中的XML文件:如何在xml中搜索關鍵字並用Python替換它的值?

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

我要做到以下幾點:

  1. 檢查通過的所有行是「應用程序名稱」存在
  2. 如果是這樣,看看是否值匹配「測試」
  3. 如果是的話,請用值「刪除我」

目前,我有:

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

這樣做的最佳方法是什麼?我遇到很多問題。

回答

2

您試過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) 
+0

是啊,我真的想切換到美麗的湯,這個問題越來越我工作的地方批准。所以現在,我無法使用它。 – david

+0

哎唷!看到我的更新。 –

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 
+0

你怎麼知道,那op有一臺* nix機器? –

+0

我不知道。命令語法應該足夠相似,不是嗎?即使op的機器根本沒有sed,操作的目的也很明確。 –