-1

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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Pedro
  • 3
  • 4

1 Answers1

0

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.

JasonPlutext
  • 15,352
  • 4
  • 44
  • 84
  • When I replace the angle brackets with "$lt" and "&gt" I get the following error. Am I missing something? Thanks for the help. org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 4769; The reference to entity "lts11:Envelope" must end with the ';' delimiter. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177) at .... at java.lang.Thread.run(Thread.java:745) javax.xml.bind.UnmarshalException – Pedro Mar 29 '16 at 09:39
  • This code I'm using: System.out.println("Creating a template request for each port type: " + filename); for( StringWriter sw : wsdlHelper.getWSDLTemplateRequest() ) { addHashMapping("API REQUEST", sw.toString().replace("<", "#1#").replace(">", "#2#")); } – Pedro Mar 29 '16 at 09:47
  • An entity reference (eg < ) ends with a semi colon; don't omit it. That's why the exception says "must end with the ';' delimiter" – JasonPlutext Mar 29 '16 at 10:19
  • Thanks for the help @JasonPlutext that solved my problem! Marking as the answer. – Pedro Mar 29 '16 at 14:33