【发布时间】:2018-06-27 17:07:10
【问题描述】:
我是 Python 新手,所以如果之前已经介绍过这个问题并且我太无知而无法应用该解决方案,我深表歉意。
这是 XML:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>DEFAULT</groupId>
<artifactId>ADP_ServiceTechnology-JRG_Testing</artifactId>
<version>2.0.31</version>
<dependencies>
<dependency>
<groupId>DEFAULT</groupId>
<artifactId>ADP Standard Operations</artifactId>
<version>2.2.86.17-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>DEFAULT</groupId>
<artifactId>Base</artifactId>
<version>1.9.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>DEFAULT</groupId>
<artifactId>Databases</artifactId>
<version>[1.1.0]</version>
</dependency>
<dependency>
<groupId>DEFAULT</groupId>
<artifactId>HPE Solutions</artifactId>
<version>[1.8.2]</version>
</dependency>
<dependency>
<groupId>DEFAULT</groupId>
<artifactId>Business Applications</artifactId>
<version>[1.3.0]</version>
</dependency>
<dependency>
<groupId>DEFAULT</groupId>
<artifactId>Operating Systems</artifactId>
<version>[1.3.0]</version>
</dependency>
</dependencies>
</project>
我成功导入数据:
import xml.etree.ElementTree as ET
tree = ET.parse('pom.xml')
root = tree.getroot()
我只需要遍历树并检索 <artifactId> 和
<version> 值。我尝试了许多在网上找到的方法,但都没有运气。使用 php 和 xpath 对我来说很简单,但是 python 让我很难过。
这个:
for elem in tree.iter():
print "%s: '%s'" % (elem.tag, elem.text)
将返回每个元素标记和文本,但我只想导航到我指出的两个。
提前致谢!
【问题讨论】: