Reputation: 825
I want to parse StringIO in form of xml with etree, hovever I have following error. Example:
import xml.etree.ElementTree
from io import StringIO
def main():
in_mem_file = StringIO()
in_mem_file.write('<?xml version="1.0" encoding="UTF-8"?>')
in_mem_file.write('<tag>')
in_mem_file.write('</tag>')
print(in_mem_file.getvalue())
e = xml.etree.ElementTree.parse(in_mem_file).getroot()
This raises following error:
xml.etree.ElementTree.ParseError: no element found: line 1, column 0
Upvotes: 2
Views: 2527
Reputation: 1
You have to reset the cursor position of the StringIO object before handing it to ET:
in_mem_file = StringIO()
in_mem_file.write('<?xml version="1.0" encoding="UTF-8"?>')
in_mem_file.write('<tag>')
in_mem_file.seek(0)
Upvotes: 0
Reputation: 50947
Provide the whole XML document when creating the StringIO
object. Using write()
does not work (but I don't have an explanation for that).
import xml.etree.ElementTree as ET
from io import StringIO
XML = """<?xml version="1.0" encoding="UTF-8"?>
<tag>
</tag>"""
in_mem_file = StringIO(XML)
tree = ET.parse(in_mem_file)
Upvotes: 3