Effective base class for all custom element classes. Adds standardized behavior to all classes in one place.
| 662 | |
| 663 | # -- lxml typing isn't quite right here, just ignore this error on _Element -- |
| 664 | class BaseOxmlElement(etree.ElementBase, metaclass=MetaOxmlElement): |
| 665 | """Effective base class for all custom element classes. |
| 666 | |
| 667 | Adds standardized behavior to all classes in one place. |
| 668 | """ |
| 669 | |
| 670 | def __repr__(self): |
| 671 | return "<%s '<%s>' at 0x%0x>" % ( |
| 672 | self.__class__.__name__, |
| 673 | self._nsptag, |
| 674 | id(self), |
| 675 | ) |
| 676 | |
| 677 | def first_child_found_in(self, *tagnames: str) -> _Element | None: |
| 678 | """First child with tag in `tagnames`, or None if not found.""" |
| 679 | for tagname in tagnames: |
| 680 | child = self.find(qn(tagname)) |
| 681 | if child is not None: |
| 682 | return child |
| 683 | return None |
| 684 | |
| 685 | def insert_element_before(self, elm: ElementBase, *tagnames: str): |
| 686 | successor = self.first_child_found_in(*tagnames) |
| 687 | if successor is not None: |
| 688 | successor.addprevious(elm) |
| 689 | else: |
| 690 | self.append(elm) |
| 691 | return elm |
| 692 | |
| 693 | def remove_all(self, *tagnames: str) -> None: |
| 694 | """Remove child elements with tagname (e.g. "a:p") in `tagnames`.""" |
| 695 | for tagname in tagnames: |
| 696 | matching = self.findall(qn(tagname)) |
| 697 | for child in matching: |
| 698 | self.remove(child) |
| 699 | |
| 700 | @property |
| 701 | def xml(self) -> str: |
| 702 | """XML string for this element, suitable for testing purposes. |
| 703 | |
| 704 | Pretty printed for readability and without an XML declaration at the top. |
| 705 | """ |
| 706 | return serialize_for_reading(self) |
| 707 | |
| 708 | def xpath(self, xpath_str: str) -> Any: # pyright: ignore[reportIncompatibleMethodOverride] |
| 709 | """Override of `lxml` _Element.xpath() method. |
| 710 | |
| 711 | Provides standard Open XML namespace mapping (`nsmap`) in centralized location. |
| 712 | """ |
| 713 | return super().xpath(xpath_str, namespaces=_nsmap) |
| 714 | |
| 715 | @property |
| 716 | def _nsptag(self) -> str: |
| 717 | return NamespacePrefixedTag.from_clark_name(self.tag) |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…