如何通过python xml元素更新避免名称空间前缀修改

时间:2015-10-06 17:11:11

标签: python

我正在编辑下面的pom.xml文件。编辑完成后,元素上的名称空间prefix将被修改。我该如何避免这种情况?

之前

  <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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.tds.adm.metasolv.BroadBandProvisioning</groupId>
  <artifactId>xxy-parent</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>BroadBandProvisioning-parent</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

后:

<ns0:project xmlns:ns0="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/maven-v4_0_0.xsd">
  <ns0:modelVersion>4.0.0</ns0:modelVersion>
  <ns0:groupId>net.tds.adm.metasolv.BroadBandProvisioning</ns0:groupId>
  <ns0:artifactId>xxy-parent</ns0:artifactId>
  <ns0:packaging>POM</ns0:packaging>
  <ns0:version>1.0-SNAPSHOT</ns0:version>
  <ns0:name>BroadBandProvisioning-parent</ns0:name>
  <ns0:url>http://maven.apache.org</ns0:url>
  <ns0:dependencies>
    <ns0:dependency>
      <ns0:groupId>junit</ns0:groupId>
      <ns0:artifactId>junit</ns0:artifactId>
      <ns0:version>3.8.1</ns0:version>
      <ns0:scope>test</ns0:scope>
    </ns0:dependency>
  </ns0:dependencies>
</ns0:project>

使用python脚本

import xml.etree.ElementTree as ET

ns = {'ns': 'http://maven.apache.org/POM/4.0.0'}

tree = ET.parse('pom.xml')
root = tree.getroot()

for child in root.findall('ns:packaging',ns):
    print(child.tag+'-' +child.text)
    newPackaging = 'POM'
    child.text = str(newPackaging)

tree.write('pom.xml')

0 个答案:

没有答案