【问题标题】:Not recursive (single node level) getElementsByTagName in Python xml.domPython xml.dom 中的非递归(单节点级别)getElementsByTagName
【发布时间】: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-&gt;groupId,而不是project-&gt;parent-&gt;groupId),我使用:

xmldoc = minidom.parse('pom.xml')
groupId = xmldoc.getElementsByTagName("groupId")[0].childNodes[0].nodeValue

但不幸的是,无论层次结构级别如何,都会在文件中找到groupId 的第一个物理匹配项,即project-&gt;parent-&gt;groupId。我实际上只想在特定节点级别而不是在其子节点中进行非递归查找。有没有办法在xml.dom 中做到这一点?

更新:我切换到BeautifulSoup,但隐式递归遍历仍然存在同样的问题:Finding a nonrecursive DOM subnode in Python using BeautifulSoup

【问题讨论】:

    标签: python xml dom


    【解决方案1】:

    您可以遍历 getElementsByTagName() 结果并获取位于根级别的第一个元素:

    group_id_element =  next(element for element in xmldoc.getElementsByTagName("groupId")
                             if element.parentNode == xmldoc.documentElement)
    
    print group_id_element.childNodes[0].nodeValue
    

    请注意,使用ElementTree 做同样的事情会更容易、更短、更快,它也是标准库的一部分。

    希望对您有所帮助。

    【讨论】:

    猜你喜欢
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-08-12
    • 2014-02-04
    • 2012-01-26
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多