Python Minidom XML 查询

标签 python xml minidom

我正在尝试使用 lxml 查询此 XML:

<lista_tareas>
    <tarea id="1" realizzato="False" data_limite="12/10/2012" priorita="1">
    <description>XML TEST</description>
</tarea>
<tarea id="2" realizzato="False" data_limite="12/10/2012" priorita="1">
    <description>XML TEST2</description>
</tarea>

我写了这段代码:

from lxml import etree
doc = etree.parse(file_path)    

root = etree.Element("lista_tareas")

for x in root:
    z = x.Element("tarea")
    for y in z:
        element_text = y.Element("description").text
        print element_text

它不打印任何东西,你能建议我怎么做吗?

最佳答案

您不想使用 minidom;使用 ElementTree API反而。 DOM API 是一个非常冗长且受限的 API,而 ElementTree API 则发挥了 Python 的优势。

MiniDOM 模块不提供您正在寻找的任何查询 API。

您可以使用捆绑的 xml.etree.ElementTree 模块,或者您可以安装 lxml ,它提供了更强大的 XPath 和其他查询选项。

import xml.etree.ElementTree as ET
root = ET.parse('document.xml').getroot()

for c in root.findall("./Root_Node[@id='1']/sub_node"):
    # Do something with c

关于Python Minidom XML 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12815637/

相关文章:

.net - 不同子命名空间中的类都出现在 WSDL 的顶层

python minidom创建带有结束标签的xml元素

python - XML:如何通过属性值获取元素 - Python 2.7 和 minidom

python - 在minidom python中添加具有属性的元素

python - ttk TreeView : selected color

python - 正则表达式:如果组在文本中只有一次则匹配

python - django-social-auth : custom response during pipeline execution

Python 到 .bat 的转换

xml - XSL FO Docbook 内容左边距

c# - 通过 StringBuilder 使用 XmlWriter 序列化的 XML 是 utf-16,而通过 Stream 是 utf-8?