builtins.TypeError: reading file objects must return plain strings : Error in Xpath - python

限于喜欢 提交于 2019-12-13 20:48:25

问题


Here's my code :

import os
os.chdir('d:/py/xml/')


from lxml import etree
from io import StringIO

#----------------------------------------------------------------------
def parseXML(xmlFile):
    """
    Parse the xml
    """
    f = open(xmlFile)
    xml = f.read()
    f.close()

    tree = etree.parse(StringIO(xml))
    context = etree.iterparse(StringIO(xml))
    for action, elem in context:
        if not elem.text:
            text = 'None'
        else:
            text = elem.text
        print (elem.tag + ' => ' + text)

if __name__ == "__main__":
    parseXML("example.xml")

I am trying to extract this xml file below :

    <?xml version="1.0" ?>
<zAppointments reminder="15">
    <appointment>
        <begin>1181251680</begin>
        <uid>040000008200E000</uid>
        <alarmTime>1181572063</alarmTime>
        <state></state>
        <location></location>
        <duration>1800</duration>
        <subject>Bring pizza home</subject>
    </appointment>
    <appointment>
        <begin>1234360800</begin>
        <duration>1800</duration>
        <subject>Check MS Office website for updates</subject>
        <location></location>
        <uid>604f4792-eb89-478b-a14f-dd34d3cc6c21-1234360800</uid>
        <state>dismissed</state>
  </appointment>
</zAppointments>

Got this error, not sure what I have done wrong , please help.

builtins.TypeError: reading file objects must return plain strings

Thanks,


回答1:


import os
os.chdir('d:/py/xml/')


from lxml import etree
#from io import StringIO

#----------------------------------------------------------------------
def parseXML(xmlFile):
    """
    Parse the xml
    """
    f = open(xmlFile)
    #xml = f.read()
    #f.close()

    #tree = etree.parse(StringIO(xml))
    context = etree.iterparse(f)
    for action, elem in context:
        if not elem.text:
            text = 'None'
        else:
            text = elem.text
        print (elem.tag + ' => ' + text)

if __name__ == "__main__":
    parseXML("example.xml")

So here's the final code just in case someone needs it, Thank you Blckknght



来源:https://stackoverflow.com/questions/12148166/builtins-typeerror-reading-file-objects-must-return-plain-strings-error-in-xp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!