aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/zwobble/mammoth/docx/BodyXmlReader.java
blob: a61e4dd3d52741d6e20b0c67b499dbaa87a5cc42 (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
package org.zwobble.mammoth.docx;

import com.google.common.collect.ImmutableList;
import org.zwobble.mammoth.documents.*;
import org.zwobble.mammoth.xml.XmlElement;
import org.zwobble.mammoth.xml.XmlElementLike;
import org.zwobble.mammoth.xml.XmlNode;

import java.util.List;
import java.util.Optional;

import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.transform;

public class BodyXmlReader {
    private final Styles styles;

    public BodyXmlReader(Styles styles) {
        this.styles = styles;
    }

    public List<DocumentElement> readElement(XmlElement element) {
        switch (element.getName()) {
            case "w:t":
                return ImmutableList.of(new Text(element.innerText()));
            case "w:r":
                return ImmutableList.of(new Run(readElements(element.children())));
            case "w:p":
                return ImmutableList.of(readParagraph(element));

            case "w:pPr":
                return ImmutableList.of();

            default:
                // TODO: emit warning
                return ImmutableList.of();
        }
    }

    public List<DocumentElement> readElements(Iterable<XmlNode> nodes) {
        return ImmutableList.copyOf(
            concat(
                transform(
                    filter(nodes, XmlElement.class),
                    this::readElement)));
    }

    private Paragraph readParagraph(XmlElement element) {
        return new Paragraph(readParagraphStyle(element), readElements(element.children()));
    }

    private Optional<Style> readParagraphStyle(XmlElement paragraph) {
        XmlElementLike properties = paragraph.findChildOrEmpty("w:pPr");
        return properties.findChildOrEmpty("w:pStyle").getAttributeOrNone("w:val")
            .map(styleId -> styles.findParagraphStyleById(styleId).orElse(new Style(styleId, Optional.empty())));
    }
}