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