Search code examples
javaxmlms-wordhashmapdocx4j

Docx4j writes XML as default in a Word document


I'm trying to write simple text (String) to a Word document by replacing variables in a Word template with the following code:

MainDocumentPart documentPart = template.getMainDocumentPart();
        try {
            documentPart.variableReplace(replaceHashMap);
        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (Docx4JException e) {
            e.printStackTrace();
        }

And in my Main class I've something like this:

for( StringWriter sw : wsdlHelper.getWSDLTemplateRequest() )
        {
            document.addHashMapping("API REQUEST", sw.toString().replace("<", "#1#").replace(">", "#2#"));
        }

I'm replacing in the String "<" with "#1#" and ">" with "#2#" for test purposes and it works flawlessly.

But I if I remove these replacements Docx4j interprets the String as a XML, sometimes even notifies of unclosed tags and the output document in the place of the chosen variable (API REQUEST) is empty!

I just need it to interpret as a String and write to the Word document as plain text "as is". I'm trying to write the request template of a Webservice as simple text, is there also a way to pretty print it directly in the document?


Solution

  • Your document should contain variables of the form ${VAR}.

    The document is marshalled to a string (containing XML).

    Sub-strings of the form ${VAR} are then replaced with whatever you have specified.

    Typically that would be simple text, not XML. If you want an angle bracket '<' to appear in your output, use &lt;

    The result is then unmarshalled. Unexpected content is dropped.