Python POM 解析器替换文本

Python POM parser replace text

xml enter image description here

我需要更改屏幕上标记的版本。

我试试:

with open(PathPom,'r') as f:

    tree = ET.parse(f)
    root = tree.getroot()

    for elem in root.getiterator():
        try:
        elem.text = elem.text.replace('1.4.1', '5.0.0')
        except AttributeError:
        pass

tree.write(PathPom,xml_declaration=True, method='xml')

pom 中的所有版本 1.4.1 都被替换,文档中的所有行都以 <ns0

开头

你知道怎么解决吗?

<?xml version="1.0" encoding="UTF-8"?>
<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>
    <groupId>cterminal</groupId>
    <artifactId>Monitor</artifactId>
    <version>1.4.1</version>
    <packaging>lba</packaging>
    <properties>
        <lb.middlewareVersion>1.7.0</lb.middlewareVersion>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>.maven</groupId>
                <artifactId>lba-maven-plugin</artifactId>
                <version>${lb.middlewareVersion}</version>
                <extensions>true</extensions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>1.4.1</version>
                <executions>
                    <execution>
                        <id>enforce-maven</id>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                        <configuration>
                            <rules>
                                <requireMavenVersion>
                                    <message>The lba-maven-plugin requires Maven version to be at
                                        least 3.1.1!</message>
                                    <version>[3.1.1,)</version>
                                </requireMavenVersion>
                                <dependencyConvergence/>
                            </rules>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

要防止 ElementTree 添加 ns0 前缀,您需要在解析 XML 之前将默认名称空间映射到空前缀。由于只有一个元素要更新,您可以使用 find() 轻松获取该元素:

....
ET.register_namespace('', 'http://maven.apache.org/POM/4.0.0')
tree = ET.parse(f)
root = tree.getroot()

version = root.find('{http://maven.apache.org/POM/4.0.0}version')
version.text = '5.0.0'
....