Generic element structure builder. This builder converts a sequence of start, data, and end method calls to a well-formed element structure. You can use this class to build an element structure using a custom XML parser, or a parser for some other XML-like format. *element_fac
| 1400 | |
| 1401 | |
| 1402 | class TreeBuilder: |
| 1403 | """Generic element structure builder. |
| 1404 | |
| 1405 | This builder converts a sequence of start, data, and end method |
| 1406 | calls to a well-formed element structure. |
| 1407 | |
| 1408 | You can use this class to build an element structure using a custom XML |
| 1409 | parser, or a parser for some other XML-like format. |
| 1410 | |
| 1411 | *element_factory* is an optional element factory which is called |
| 1412 | to create new Element instances, as necessary. |
| 1413 | |
| 1414 | *comment_factory* is a factory to create comments to be used instead of |
| 1415 | the standard factory. If *insert_comments* is false (the default), |
| 1416 | comments will not be inserted into the tree. |
| 1417 | |
| 1418 | *pi_factory* is a factory to create processing instructions to be used |
| 1419 | instead of the standard factory. If *insert_pis* is false (the default), |
| 1420 | processing instructions will not be inserted into the tree. |
| 1421 | """ |
| 1422 | def __init__(self, element_factory=None, *, |
| 1423 | comment_factory=None, pi_factory=None, |
| 1424 | insert_comments=False, insert_pis=False): |
| 1425 | self._data = [] # data collector |
| 1426 | self._elem = [] # element stack |
| 1427 | self._last = None # last element |
| 1428 | self._root = None # root element |
| 1429 | self._tail = None # true if we're after an end tag |
| 1430 | if comment_factory is None: |
| 1431 | comment_factory = Comment |
| 1432 | self._comment_factory = comment_factory |
| 1433 | self.insert_comments = insert_comments |
| 1434 | if pi_factory is None: |
| 1435 | pi_factory = ProcessingInstruction |
| 1436 | self._pi_factory = pi_factory |
| 1437 | self.insert_pis = insert_pis |
| 1438 | if element_factory is None: |
| 1439 | element_factory = Element |
| 1440 | self._factory = element_factory |
| 1441 | |
| 1442 | def close(self): |
| 1443 | """Flush builder buffers and return toplevel document Element.""" |
| 1444 | assert len(self._elem) == 0, "missing end tags" |
| 1445 | assert self._root is not None, "missing toplevel element" |
| 1446 | return self._root |
| 1447 | |
| 1448 | def _flush(self): |
| 1449 | if self._data: |
| 1450 | if self._last is not None: |
| 1451 | text = "".join(self._data) |
| 1452 | if self._tail: |
| 1453 | assert self._last.tail is None, "internal error (tail)" |
| 1454 | self._last.tail = text |
| 1455 | else: |
| 1456 | assert self._last.text is None, "internal error (text)" |
| 1457 | self._last.text = text |
| 1458 | self._data = [] |
| 1459 |
no outgoing calls
no test coverage detected
searching dependent graphs…