Python Minidom XML 查询 [英] Python Minidom XML Query

查看:25
本文介绍了Python Minidom XML 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to query this XML with lxml:

<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

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

It doesn't print anything, could you suggest me how to do?

推荐答案

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

You do not want to use the minidom; use the ElementTree API instead. The DOM API is a very verbose and constrained API, the ElementTree API plays to Python's strengths instead.

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

The MiniDOM module doesn't offer any query API like you are looking for.

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

You can use the bundled xml.etree.ElementTree module, or you could install lxml, which offers more powerful XPath and other query options.

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 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆