Python use lxml with fileinput

Viewed 575

Having a simple xml

<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <child>abc</child>
</root>

I wanted to parse it from file and this works well:

with open('tst.xml') as test_xml:
    for _, element in lxml.etree.iterparse(test_xml, tag='child'):
        print element.text # prints abc as expected

However, I tried to modify script then to allow it parse xml either from file or from stdin and did not succeed:

fi = fileinput.input('tst.xml')
for _, element in lxml.etree.iterparse(fi, tag='child'):
    print element.text

# File "iterparse.pxi", line 371, in lxml.etree.iterparse.__init__ (src/lxml/lxml.etree.c:97283)
# File "apihelpers.pxi", line 1411, in lxml.etree._encodeFilename (src/lxml/lxml.etree.c:22515)
# TypeError: Argument must be string or unicode.

I'm not sure in what I'm doing wrong. Is the FileInput object not a file-like object in python?

2 Answers
Related