Is there an elegant way to count tag elements in a xml file using lxml in python?(有没有一种优雅的方法可以在 python 中使用 lxml 来计算 xml 文件中的标签元素?)
问题描述
我可以将 xml 文件的内容读取为字符串并使用字符串操作来实现这一点,但我想有一种更优雅的方法可以做到这一点.由于我在文档中没有找到线索,所以我在这里:
I could read the content of the xml file to a string and use string operations to achieve this, but I guess there is a more elegant way to do this. Since I did not find a clue in the docus, I am sking here:
给定一个 xml(见下文)文件,您如何计算 xml 标签,例如 count of author-tags 在下面的示例中,最优雅的方式? 我们假设每个作者只出现一次.
Given an xml (see below) file, how do you count xml tags, like count of author-tags in the example bewlow the most elegant way? We assume, that each author appears exactly once.
<root>
<author>Tim</author>
<author>Eva</author>
<author>Martin</author>
etc.
</root>
这个xml文件很琐碎,但有可能,作者并不总是一个接一个地列出来,他们之间可能还有其他的标签.
This xml file is trivial, but it is possible, that the authors are not always listed one after another, there may be other tags between them.
推荐答案
如果要统计所有作者标签:
If you want to count all author tags:
import lxml.etree
doc = lxml.etree.parse(xml)
count = doc.xpath('count(//author)')
这篇关于有没有一种优雅的方法可以在 python 中使用 lxml 来计算 xml 文件中的标签元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有一种优雅的方法可以在 python 中使用 lxml 来计算 xml 文件中的标签元素?
基础教程推荐
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
