Load external XML document into element tree. *source* is a file name or file object, *parser* is an optional parser instance that defaults to XMLParser. ParseError is raised if the parser fails to parse the document. Returns the root element of the given source do
(self, source, parser=None)
| 551 | self._root = element |
| 552 | |
| 553 | def parse(self, source, parser=None): |
| 554 | """Load external XML document into element tree. |
| 555 | |
| 556 | *source* is a file name or file object, *parser* is an optional parser |
| 557 | instance that defaults to XMLParser. |
| 558 | |
| 559 | ParseError is raised if the parser fails to parse the document. |
| 560 | |
| 561 | Returns the root element of the given source document. |
| 562 | |
| 563 | """ |
| 564 | close_source = False |
| 565 | if not hasattr(source, "read"): |
| 566 | source = open(source, "rb") |
| 567 | close_source = True |
| 568 | try: |
| 569 | if parser is None: |
| 570 | # If no parser was specified, create a default XMLParser |
| 571 | parser = XMLParser() |
| 572 | if hasattr(parser, '_parse_whole'): |
| 573 | # The default XMLParser, when it comes from an accelerator, |
| 574 | # can define an internal _parse_whole API for efficiency. |
| 575 | # It can be used to parse the whole source without feeding |
| 576 | # it with chunks. |
| 577 | self._root = parser._parse_whole(source) |
| 578 | return self._root |
| 579 | while data := source.read(65536): |
| 580 | parser.feed(data) |
| 581 | self._root = parser.close() |
| 582 | return self._root |
| 583 | finally: |
| 584 | if close_source: |
| 585 | source.close() |
| 586 | |
| 587 | def iter(self, tag=None): |
| 588 | """Create and return tree iterator for the root element. |