2017-08-16 55 views
1

我想在python 3中使用xml.etree構建一個腳本,它接受版本作爲參數,解析xml並將xml標記中的值+樹中的值替換爲根和他的樹兒童。Python xml.etree問題

我在我可以更改根目錄中的默認值,但我正在努力改變版本childs和孫子--CurrentVersion,模板和基地。

這裏是我的代碼和XML:

代碼 -

import sys 
from xml.etree import ElementTree as et 
version = sys.argv[1] 
parse = et.parse("WebApp2.config") 
root = parse.getroot() 

def changeVersion(version): 
    ourVersion = root.find('OurVersion') 
    root.set("default", version) 
    print(et.tostring(root)) 
    parse.write("WebApp2.config", xml_declaration=True) 

if __name__ == "__main__": 
    changeVersion(version) 

XML的

<?xml version="1.0"?> 
<OurVersion default="1.0.0.3"> 
    <CurrentVersion bitSupport="true" deviceDetectionSupport="true" 
    version="1.0.0.3"> 
    <Template>D:\Some\Path\Software\1.0.0.3\webApp\index.webapp</Template> 
    <BasePath>resources/1.0.0.3/webApp/</BasePath> 
    </CurrentVersion> 
</OurVersion> 

我試圖添加類似下面的,但即時通訊得到「沒有設置爲currentVersion」的問題 -

ourVersion = root.find('OurVersion') 
ourVersion.set('default`, version) 
currentVersion = ourVersion.find('CurrentVersion') 
currentVersion.set('version', version) 

欣賞你對此事的幫助;)

回答

0

你的第一個腳本的作品,因爲與root.set("default", version)您使用root指您要修改的屬性default

事實上ourVersion = root.find('OurVersion')返回任何(None),因爲 OurVersion你的根,然後ourVersion.find('CurrentVersion')不能返回你所期望的。

試試這個:

currentVersion = root.find('CurrentVersion') 
currentVersion.set('version', version) 
+0

非常感謝!我怎麼能也參考標籤內的文本,並找到一個特定的字符串呢?我的意思是改變模板和BasePath? – JamZ

+0

你可以使用'currentVersion.find('Template')。text' – PRMoureu