Python xml ElementTree from a string source?

前端 未结 4 400
猫巷女王i
猫巷女王i 2020-12-12 15:40

The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string?

Maybe I am missing something here, but there must be a way to

相关标签:
4条回答
  • 2020-12-12 15:46

    io.StringIO is another option for getting XML into xml.etree.ElementTree:

    import io
    f = io.StringIO(xmlstring)
    tree = ET.parse(f)
    root = tree.getroot()
    

    Hovever, it does not affect the XML declaration one would assume to be in tree (although that's needed for ElementTree.write()). See How to write XML declaration using xml.etree.ElementTree.

    0 讨论(0)
  • 2020-12-12 15:59

    If you're using xml.etree.ElementTree.parse to parse from a file, then you can use xml.etree.ElementTree.fromstring to parse from text.

    See xml.etree.ElementTree

    0 讨论(0)
  • 2020-12-12 16:08

    You need the xml.etree.ElementTree.fromstring(text)

    from xml.etree.ElementTree import XML, fromstring
    myxml = fromstring(text)
    
    0 讨论(0)
  • 2020-12-12 16:10

    You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.

    import xml.etree.ElementTree as ET
    tree = ET.ElementTree(ET.fromstring(xmlstring))
    

    I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse() and fromstring() methods.

    0 讨论(0)
提交回复
热议问题