Ananymous
Ananymous

Reputation: 91

Python lxml and stdin

I have a xml file, book.xml (http://msdn.microsoft.com/en-us/library/ms762271(VS.85).aspx)

I would like to cat books.xml and get all book ids and genres for the book id.

Similar to

cat books.xml | python reader.py

Any tips or help would be appreciated. Thanks.

Upvotes: 5

Views: 3633

Answers (1)

kennytm
kennytm

Reputation: 523264

To read an XML file from stdin, just use etree.parse. This function accepts a file object, which can be sys.stdin.

import sys
from lxml import etree

tree = etree.parse(sys.stdin)

print ( [(b.get('id'), b.findtext('genre')) for b in tree.iterfind('book')] )

Upvotes: 12

Related Questions