Python xml.etree问题

Python xml.etree问题,python,xml,Python,Xml,我正在尝试使用xml.etree在Python3中构建一个脚本,它接受version作为参数,解析xml并替换xml标记中的版本+从树到根及其子代的值 我现在可以更改根目录中的默认值,但我正在努力将版本更改为childs和sunders-CurrentVersion、Template和Base 以下是我的代码和XML: 代码- import sys from xml.etree import ElementTree as et version = sys.argv[1] parse = et.p

我正在尝试使用xml.etree在Python3中构建一个脚本,它接受version作为参数,解析xml并替换xml标记中的版本+从树到根及其子代的值

我现在可以更改根目录中的默认值,但我正在努力将版本更改为childs和sunders-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 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>
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 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>

感谢您在这件事上的帮助;)

您的第一个脚本可以工作,因为使用
root.set(“default”,version)
您正在使用
root
来引用要修改的属性
default

事实上,
ourVersion=root.find('ourVersion')
不返回任何内容(
None
),因为
OurVersion
是您的根目录,然后
OurVersion.find('CurrentVersion')
无法返回您期望的内容

请尝试以下方法:

currentVersion = root.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)

非常感谢!!我怎样才能引用标记中的文本并在那里找到特定的字符串?我的意思是更改模板和基本路径?您可以使用
currentVersion.find('Template')。text
非常感谢!!我怎样才能引用标记中的文本并在那里找到特定的字符串?我的意思是更改模板和基本路径?您可以使用
currentVersion.find('Template')。text