我试图使用xml.etree在python 3中构建一个脚本,它接受版本作为参数,解析xml并替换从树到根和他的子树的xml标记+值中的版本。
我到了可以在根目录中更改默认值的地步,但我很难将版本更改为childs和grandchilds CurrentVersion、Template和Base。
下面是我的代码和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)(感谢你在这件事上的帮助;)
发布于 2017-08-16 22:15:16
您的第一个脚本可以工作,因为在root.set("default", version)中,您使用root来引用您想要修改的属性default。
事实上,ourVersion = root.find('OurVersion')不返回任何内容(None),因为OurVersion 是的根,而ourVersion.find('CurrentVersion')则不能返回您期望的内容。
试一试:
currentVersion = root.find('CurrentVersion')
currentVersion.set('version', version)https://stackoverflow.com/questions/45723615
复制相似问题