【发布时间】:2014-02-04 07:52:13
【问题描述】:
有没有办法只在单个节点级别而不是递归地使用getElementsByTagName?
例如考虑解析pom.xml 文件:
<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">
<parent>
<groupId>com.parent</groupId>
<artifactId>parent</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>2.0.0</modelVersion>
<groupId>com.parent.somemodule</groupId>
<artifactId>some_module</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Some Module</name>
...
如果我想在顶层获得groupId(特别是project->groupId,而不是project->parent->groupId),我使用:
xmldoc = minidom.parse('pom.xml')
groupId = xmldoc.getElementsByTagName("groupId")[0].childNodes[0].nodeValue
但不幸的是,无论层次结构级别如何,都会在文件中找到groupId 的第一个物理匹配项,即project->parent->groupId。我实际上只想在特定节点级别而不是在其子节点中进行非递归查找。有没有办法在xml.dom 中做到这一点?
更新:我切换到BeautifulSoup,但隐式递归遍历仍然存在同样的问题:Finding a nonrecursive DOM subnode in Python using BeautifulSoup
【问题讨论】: