aboutsummaryrefslogtreecommitdiff
path: root/mammoth/docx/document_xml.py
blob: 1c9a43b22f5900877cab6462b3493bc4fc1c7071 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from .. import documents
from .xmlparser import node_types


_handlers = {}


def handler(name):
    def add(func):
        _handlers[name] = func
        
    return add


def read_document_xml_element(element):
    handler = _handlers.get(element.name)
    if handler is None:
        return None
    else:
        return handler(element)


@handler("w:t")
def text(element):
    return documents.Text(_inner_text(element))


@handler("w:r")
def run(element):
    return documents.Run(_read_xml_elements(element.children))


@handler("w:p")
def paragraph(element):
    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)


@handler("w:body")
def body(element):
    return _read_xml_elements(element.children)


@handler("w:document")
def document(element):
    body_element = _find_child(element, "w:body")
    return documents.Document(_read_xml_elements(body_element.children))


def _find(predicate, iterable):
    for item in iterable:
        if predicate(item):
            return item


def _find_child(element, name):
    return _find(lambda child: child.name == name, element.children)


def _read_xml_elements(elements):
    return filter(None, map(read_document_xml_element, elements))


def _inner_text(node):
    if node.node_type == node_types.text:
        return node.value
    else:
        return "".join(_inner_text(child) for child in node.children)