javadocx4jwordprocessingml

How to succinctly extract text from a docx4j run?


I want to extract text from runs in a document.xml using docx4j from a DOCX file like this:

<w:document mc:Ignorable="w14 w15 w16se wp14">
<w:body>
<w:r>
  <w:rPr>
    <w:rFonts w:ascii="TimesNewRomanRegular" w:hAnsi="TimesNewRomanRegular" w:cs="TimesNewRomanRegular"/>
    <w:b/>
    <w:sz w:val="19"/>
    <w:szCs w:val="19"/>
    <w:lang w:val="en-US"/>
  </w:rPr>
  <w:t>CEO</w:t>
</w:r>
...

I extracted the runs and now I want to get the text of each run. The code below works but is extremely verbose. Is it possible to get the text of an instance of org.docx4j.wml.R in a more succinct manner?

public static Optional<String> runText(org.docx4j.wml.R run)
{
        return run.getContent()
                .stream()
                .map(JAXBElement.class::cast)
                .map(JAXBElement::getValue)
                .filter(Text.class::isInstance)
                .map(Text.class::cast)
                .map(Text::getValue)
                .findFirst();
}

While "R::getContent" and "R::getRPr" exist, I wonder why "R::getText" doesn't exist in a text document.


Solution

  • See https://github.com/plutext/docx4j/blob/master/docx4j-core/src/main/java/org/docx4j/TextUtils.java#L55

    for which Javadoc:

    /**
     * Extract contents of descendant <w:t> elements. 
     * 
     * @param o
     * @return String
     * @since 6.0.0
     */