[英]Python xml.etree issue
我正在尝试使用xml.etree在python 3中构建脚本,该脚本接受version作为参数,解析xml并替换xml标记+值中的版本,从树到根及其子节点。
我可以更改根目录中的默认值,但是我正在努力将版本更改为子代和孙代-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)
感谢您在此问题上的帮助;)
您的第一个脚本起作用是因为root.set("default", version)
使用root
来引用您要修改的default
属性。
实际上ourVersion = root.find('OurVersion')
返回任何内容( None
),因为OurVersion
是您的根目录,然后ourVersion.find('CurrentVersion')
无法返回您期望的结果。
试试这个代替:
currentVersion = root.find('CurrentVersion')
currentVersion.set('version', version)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.