python操作xml

python操作xml

  1. pip3 install lxml
  2. 通过etree包的parse函数打开文件
  3. 获取到root节点
  4. 设置对应的ns
  5. 在根结点之后查找,并指定ns
  6. 对应元素的value改值
  7. 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.0modelVersion>
    <version>2.36.0version>
    <parent>
        <groupId>com.sap.gtt.v2groupId>
        <artifactId>gtt-v2-parent-pomartifactId>
        <version>[2.37.0, 2.38.0)version>
    parent>
    <properties>
        <whitesource.projectName>LBN_FND_TTWRITEwhitesource.projectName>
        <vulas.ppms.component>SAP LBN 2.0vulas.ppms.component>
        <vulas.ppms.objno.scv>xxxxxxxvulas.ppms.objno.scv>
        <maven-jar-plugin.version>3.1.1maven-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-writeserviceartifactId>
    <packaging>jarpackaging>
    <name>gtt-v2-core-inbound-writeservicename>

    <dependencies>
        <dependency>
            <groupId>org.everit.jsongroupId>
            <artifactId>org.everit.json.schemaartifactId>
        dependency>
        <dependency>
            <groupId>${project.groupId}groupId>
            <artifactId>gtt-v2-shared-libraryartifactId>
            <version>${sharedLIB.version}version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-validationartifactId>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
        dependency>

        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
        dependency>

    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>

你可能感兴趣的:(python,xml,java)