Builder which constructs document fragments given XML source text and a context node. The context node is expected to provide information about the namespace declarations which are in scope at the start of the fragment.
| 589 | |
| 590 | |
| 591 | class FragmentBuilder(ExpatBuilder): |
| 592 | """Builder which constructs document fragments given XML source |
| 593 | text and a context node. |
| 594 | |
| 595 | The context node is expected to provide information about the |
| 596 | namespace declarations which are in scope at the start of the |
| 597 | fragment. |
| 598 | """ |
| 599 | |
| 600 | def __init__(self, context, options=None): |
| 601 | if context.nodeType == DOCUMENT_NODE: |
| 602 | self.originalDocument = context |
| 603 | self.context = context |
| 604 | else: |
| 605 | self.originalDocument = context.ownerDocument |
| 606 | self.context = context |
| 607 | ExpatBuilder.__init__(self, options) |
| 608 | |
| 609 | def reset(self): |
| 610 | ExpatBuilder.reset(self) |
| 611 | self.fragment = None |
| 612 | |
| 613 | def parseFile(self, file): |
| 614 | """Parse a document fragment from a file object, returning the |
| 615 | fragment node.""" |
| 616 | return self.parseString(file.read()) |
| 617 | |
| 618 | def parseString(self, string): |
| 619 | """Parse a document fragment from a string, returning the |
| 620 | fragment node.""" |
| 621 | self._source = string |
| 622 | parser = self.getParser() |
| 623 | doctype = self.originalDocument.doctype |
| 624 | ident = "" |
| 625 | if doctype: |
| 626 | subset = doctype.internalSubset or self._getDeclarations() |
| 627 | if doctype.publicId: |
| 628 | ident = ('PUBLIC "%s" "%s"' |
| 629 | % (doctype.publicId, doctype.systemId)) |
| 630 | elif doctype.systemId: |
| 631 | ident = 'SYSTEM "%s"' % doctype.systemId |
| 632 | else: |
| 633 | subset = "" |
| 634 | nsattrs = self._getNSattrs() # get ns decls from node's ancestors |
| 635 | document = _FRAGMENT_BUILDER_TEMPLATE % (ident, subset, nsattrs) |
| 636 | try: |
| 637 | parser.Parse(document, True) |
| 638 | except: |
| 639 | self.reset() |
| 640 | raise |
| 641 | fragment = self.fragment |
| 642 | self.reset() |
| 643 | ## self._parser = None |
| 644 | return fragment |
| 645 | |
| 646 | def _getDeclarations(self): |
| 647 | """Re-create the internal subset from the DocumentType node. |
| 648 |
no outgoing calls
no test coverage detected
searching dependent graphs…