python-3.x - 如何在 Python 3 中使用 lxml?

标签 python-3.x lxml

在我的项目中,我需要使用 lxml.etree 解析 XML 文档。我是 Python 的新手,所以我不明白如何找到带有某些标签的所有类别。让我们更准确地描述它。

我有一个像这样的 XML:

<cinema>
  <name>BestCinema</name>
  <films>
    <categories>
      <category>Action</category>
      <category>Thriller</category>
      <category>Soap opera</category>
    </categories>
  </films>
</cinema>

现在我需要获取所有类别的列表。在这种情况下,它将是:

      <category>Action</category>
      <category>Thriller</category>
      <category>Soap opera</category>

我需要使用:

tree = etree.parse(file)

谢谢,欢迎任何帮助。

最佳答案

它应该像这样简单:

from lxml import etree
el = etree.parse('input.xml')
categories = el.xpath("//category")
print(categories)
...

您应该在 tutorial 中找到的所有其他内容.

关于python-3.x - 如何在 Python 3 中使用 lxml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16176954/

相关文章:

python - lxml objectify 看不到根

python - 这个返回或设置变量的代码可以变得更简单吗?

Python socketio badnamespaceerror 在一台设备上出现异常,但在另一台设备上不起作用

python - 如何通过 XPath 选择一个 div 下的跨度而不是另一个 div 下的跨度?

python - 如何使用 lxml 迭代 xml 数据以删除下一个重复元素

python - 使用 lxml 和 xpath 解析 Html

python - 我如何使用字典来转换 python 中的数组?

python - 在字符串中连续添加数字

python - 是否有任何 Python3 兼容模块来读取/写入 IPTC 数据?

python - Scrapy 抓取下一页