2 years ago

#41085

test-img

Michael Fuchs

Docx4j variableReplace() with string containing "&"

Replacing '&' with & fixes the problem

I'm currently struggling with the method variableReplace() from docx4j.

Basically I'm reading in json-files and want to replace the read json properties in a word-file. My problem is, that, sometimes, some values contain the special character '&', which causes some problems.

Here's some example code:

import org.docx4j.model.datastorage.migration.VariablePrepare;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

public class exampleClass {
    private void method (){
        File templateFile = new File("resources/template_somefile.docx");
        File targetFile = new File(templateFile.getPath().replaceFirst("template_", ""));
        Files.copy(templateFile.toPath(), targetFile.toPath(), REPLACE_EXISTING);

        Map<String, String> mappings = new HashMap<String, String>();
        mappings.put("myField", "Lisa & Lotte");

        WordprocessingMLPackage wordPackage = WordprocessingMLPackage.load(targetFile);
        MainDocumentPart docPart = wordPackage.getMainDocumentPart();
        VariablePrepare.prepare(wordPackage);
        docPart.variableReplace(mappings);

        wordPackage.save(targetFile);
    }
}

Running this code causes following error:

[Fatal Error] :1:5368: Auf "&" in der Entityreferenz muss umgehend der Entityname folgen.

It says that, following a '&' there must immediately follow an entity-reference of an entityname.

At this point I'm clueless as to what to do, to combat that. As far as I understand this, the '&' is already escaped by the String.

java

docx4j

0 Answers

Your Answer

Accepted video resources