An XML element hierarchy. This class also provides support for serialization to and from standard XML. *element* is an optional root element node, *file* is an optional file handle or file name of an XML file whose contents will be used to initialize the tree with.
| 516 | |
| 517 | |
| 518 | class ElementTree: |
| 519 | """An XML element hierarchy. |
| 520 | |
| 521 | This class also provides support for serialization to and from |
| 522 | standard XML. |
| 523 | |
| 524 | *element* is an optional root element node, |
| 525 | *file* is an optional file handle or file name of an XML file whose |
| 526 | contents will be used to initialize the tree with. |
| 527 | |
| 528 | """ |
| 529 | def __init__(self, element=None, file=None): |
| 530 | if element is not None and not iselement(element): |
| 531 | raise TypeError('expected an Element, not %s' % |
| 532 | type(element).__name__) |
| 533 | self._root = element # first node |
| 534 | if file: |
| 535 | self.parse(file) |
| 536 | |
| 537 | def getroot(self): |
| 538 | """Return root element of this tree.""" |
| 539 | return self._root |
| 540 | |
| 541 | def _setroot(self, element): |
| 542 | """Replace root element of this tree. |
| 543 | |
| 544 | This will discard the current contents of the tree and replace it |
| 545 | with the given element. Use with care! |
| 546 | |
| 547 | """ |
| 548 | if not iselement(element): |
| 549 | raise TypeError('expected an Element, not %s' |
| 550 | % type(element).__name__) |
| 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 |
no outgoing calls
no test coverage detected
searching dependent graphs…