What's the functional difference between "etree.fromstring ()" and "etree.XML ()" in lxml?

lxml offers several different functions for parsing strings. Two of them, etree.fromstring()

and etree.XML()

seem to be very similar. Dokshrin for the first says that it parses "strings" and the last "string constants". Also, the XML()

docstring states:

This function can be used to embed "XML literals" into Python code, [...]

What is the functional difference between these functions? When should you use each other?

+3


source to share


1 answer


Looking at the source code , for XML()

and fromstring()

, the former has an additional piece of code:

if parser is None:
    parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
    if not isinstance(parser, XMLParser):
        parser = __DEFAULT_XML_PARSER

      



So they differ in side effects: XML()

only uses the default XML parser as the default parser. If the default parser has been changed to XMLParser

, XML()

will ignore it.

etree.set_default_parser(etree.HTMLParser())
etree.tostring(etree.fromstring("<root/>"))
# b'<html><body><root/></body></html>'
etree.tostring(etree.XML("<root/>"))
# b'<root/>'

      

+3


source







All Articles