【问题标题】:How to use lxml in Python 3?如何在 Python 3 中使用 lxml?
【发布时间】:2013-04-17 02:47:53
【问题描述】:

在我的项目中,我需要使用 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)

谢谢,欢迎任何帮助。

【问题讨论】:

    标签: python-3.x lxml


    【解决方案1】:

    应该很简单:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 2020-07-20
      • 1970-01-01
      相关资源
      最近更新 更多