Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently counting elements in a very large XML doc using lxml

Tags:

python

xml

lxml

I have a very large (1.8GB) XML document. I'd like to simply find the number of elements with the tag <Product>.

I've got this far:

context = etree.iterparse('./test.xml', tag='Product')
num_elems = 0
for event, elem in context:
    num_elems += 1
print num_elems

It works, but is there a faster way of doing it?

like image 384
flossfan Avatar asked Aug 05 '26 10:08

flossfan


1 Answers

Since this works, I take it that memory use is not an issue (iterparse will build a tree of the entire file in memory unless you prune it while iterating over the elements). In that case, save yourself the trouble of iterating and counting in Python and let LXML/libxml handle that in C:

tree = etree.parse("./test.xml")
num_elems = tree.xpath("count(//Product)")    # note: returns a float
like image 58
Fred Foo Avatar answered Aug 07 '26 23:08

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!