Python lxml library study note 4

Source: Internet
Author: User

Parser object: lxml. etree uses the standard parser with the default configuration by default. to configure the parser, you can create your own instance.

>>> Parser = etree. XMLParser (remove_blk_text = True) # lxml. etree only!

In this example, a parser is created to remove null text between tags, which can reduce the size of the tree and avoid tail, if you know that the blank content does not make any sense to you.

>>> Root = etree. XML ("<root> <a/> <B> </root>", parser)
>>> Etree. tostring (root)
B '<root> <a/> <B> </root>'
>>> For element in root. iter ("*"):
... If element. text is not None and not element. text. strip ():
... Element. text = None
>>> Etree. tostring (root)
B '<root> <a/> <B/> </root>'

Incremental Resolution:

Lxml. etree provides two methods for incremental parsing. One method is through a class object, which repeatedly calls the read () method.
>>> Class DataSource:
... Data = [B "<roo", B "t> <", B "a/", B "> <", B "/root>"]
... Def read (self, requested_size ):
... Try:
... Return self. data. pop (0)
... Handle T IndexError:
... Return B''
>>> Tree = etree. parse (DataSource ())
>>> Etree. tostring (tree)
B '<root> <a/> </root>'

The second method is provided by the feed (data) and close () methods through the feed parser interface.

>>> Parser = etree. XMLParser ()
>>> Parser. feed ("<roo ")
>>> Parser. feed ("t> <")
>>> Parser. feed ("/")
>>> Parser. feed ("> <")
>>> Parser. feed ("/root> ")

>>> Root = parser. close ()
>>> Etree. tostring (root)
'<Root> <a/> </root>'

When calling the close () method (or when an exception occurs), you can call the feed () method to re-use parser:
>>> Parser. feed ("<root/> ")
>>> Root = parser. close ()
>>> Etree. tostring (root)
B '<root/>'

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.