2012-02-29 74 views
0

這個XML文件被命名爲example.xml寫XML命名空間:的Python:閱讀和使用ElementTree的

<?xml version="1.0"?> 
<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>14.0.0</modelVersion> 
    <groupId>.com.foobar.flubber</groupId> 
    <artifactId>uberportalconf</artifactId> 
    <version>13-SNAPSHOT</version> 
    <packaging>pom</packaging> 
    <name>Environment for UberPortalConf</name> 
    <description>This is the description</description>  
    <properties> 
     <birduberportal.version>11</birduberportal.version> 
     <promotiondevice.version>9</promotiondevice.version> 
     <foobarportal.version>6</foobarportal.version> 
     <eventuberdevice.version>2</eventuberdevice.version> 
    </properties> 
    <!-- A lot more here, but as it is irrelevant for the problem I have removed it --> 
</project> 

如果我加載的example.xml文件上面使用的ElementTree和打印根節點:

>>> from xml.etree import ElementTree 
>>> tree = ElementTree.parse('example.xml') 
>>> print tree.getroot() 
<Element '{http://maven.apache.org/POM/4.0.0}project' at 0x26ee0f0> 

我看到Element還包含名稱空間http://maven.apache.org/POM/4.0.0

我如何:

  1. 獲取foobarportal.version文本,由一個增加它並寫XML文件後面,同時保持文件加載時已經命名空間,也不會改變整體XML佈局。
  2. 讓它使用任何命名空間加載,而不僅僅是http://maven.apache.org/POM/4.0.0。我仍然不想剝離命名空間,因爲我希望XML保持不變,除了更改foobarportal.version,如上面的。

目前的方法是沒有意識到XML的但滿足和以上:

  1. grep的用於<foobarportal.version>(.*)</foobarportal.version>
  2. 採取匹配組的內容和i增加1增加它
  3. 寫回來。

這將是一個很好的XML感知解決方案,因爲它會更健壯。 ElementTree的XML名稱空間處理使其更加複雜。

+0

從來就試過'樹。 getroot()。find('project')'由於命名空間而不起作用。之後,我幾乎卡住了,文檔沒有幫助我。 – Deleted 2012-02-29 15:26:57

+0

在問題中向我們展示您嘗試過的代碼。 – Marcin 2012-02-29 15:43:41

回答

2

如果你的問題很簡單:「我怎麼被命名空間中的元素名稱搜索」,那麼答案是lxml的理解{namespace}語法,所以你可以這樣做:

tree.getroot().find('{http://maven.apache.org/POM/4.0.0}project')