问题描述
我可以读取xml文件的内容到一个字符串,并使用字符串操作来实现这一点,但我想有一个更优雅的方式来做到这一点。因为我没有找到一个线索在docus,我在这里sking:
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标签, 我们假设每个作者只出现一次。
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)')
这篇关于有没有一个优雅的方式来计数标签元素在xml文件中使用python中的lxml?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!