From 833c867189d757efb5b13e1e783869a4039860de Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Sun, 1 Dec 2013 11:40:55 +0000 Subject: Create null XML element --- mammoth/docx.py | 9 ++++----- mammoth/xmlparser.py | 20 +++++++++++++++++++- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/mammoth/docx.py b/mammoth/docx.py index bf4de0b..01087ce 100644 --- a/mammoth/docx.py +++ b/mammoth/docx.py @@ -47,11 +47,10 @@ def run(element): @handler("w:p") def paragraph(element): - properties = _find_child(element, "w:pPr") - if properties is None: - style_name = None - else: - style_name = _find_child(properties, "w:pStyle").attributes.get("w:val") + properties = element.find_child_or_null("w:pPr") + style_name = properties \ + .find_child_or_null("w:pStyle") \ + .attributes.get("w:val") children = _read_xml_elements(element.children) return documents.paragraph(children, style_name) diff --git a/mammoth/xmlparser.py b/mammoth/xmlparser.py index 8b26777..d58ea75 100644 --- a/mammoth/xmlparser.py +++ b/mammoth/xmlparser.py @@ -2,7 +2,25 @@ import collections import xml.sax -XmlElement = collections.namedtuple("XmlElement", ["name", "attributes", "children"]) +XmlElementBase = collections.namedtuple("XmlElement", ["name", "attributes", "children"]) +class XmlElement(XmlElementBase): + def find_child_or_null(self, name): + for child in self.children: + if child.name == name: + return child + return _null_xml_element + + +class NullXmlElement(object): + attributes = {} + + def find_child_or_null(self, name): + return self + + +_null_xml_element = NullXmlElement() + + XmlText = collections.namedtuple("XmlText", ["value"]) -- cgit v1.2.3