python操作xml
- pip3 install lxml
- 通过etree包的parse函数打开文件
- 获取到root节点
- 设置对应的ns
- 在根结点之后查找,并指定ns
- 对应元素的value改值
- tree.write(“filePath”)
from lxml import etree
tree=etree.parse("pom.xml")
root = tree.getroot()
namespaces = {'mvn': 'http://maven.apache.org/POM/4.0.0'}
key_to_modify = 'sharedLIB.version'
element = root.find(f".//mvn:properties/mvn:{key_to_modify}", namespaces)
if element is not None:
new_value = 'new-value'
element.text = new_value
print(f"Value of '{key_to_modify}' changed to '{new_value}'")
else:
print(f"Element '{key_to_modify}' not found")
# Save the modified XML to a new file
tree.write('pom.xml', encoding='utf-8', xml_declaration=True, pretty_print=True)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<version>2.36.0</version>
<parent>
<groupId>com.sap.gtt.v2</groupId>
<artifactId>gtt-v2-parent-pom</artifactId>
<version>[2.37.0, 2.38.0)</version>
</parent>
<properties>
<whitesource.projectName>LBN_FND_TTWRITE</whitesource.projectName>
<vulas.ppms.component>SAP LBN 2.0</vulas.ppms.component>
<vulas.ppms.objno.scv>xxxxxxx</vulas.ppms.objno.scv>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
<sharedLIB.version>[2.42.0, 2.43.0)</sharedLIB.version>
<sonar.exclusions>
**/writeservice/App.java,
**/writeservice/configuration/*
</sonar.exclusions>
</properties>
<artifactId>gtt-v2-core-inbound-writeservice</artifactId>
<packaging>jar</packaging>
<name>gtt-v2-core-inbound-writeservice</name>
<dependencies>
<dependency>
<groupId>org.everit.json</groupId>
<artifactId>org.everit.json.schema</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>gtt-v2-shared-library</artifactId>
<version>${sharedLIB.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>