【问题标题】:Word found unreadable content in .docx, Adding xml in document template using docx4jWord 在 .docx 中发现不可读的内容,使用 docx4j 在文档模板中添加 xml
【发布时间】:2025-12-11 03:20:32
【问题描述】:

首先,我创建了一个文档模板文件,并从开发人员选项卡的 XML 映射窗格中向 MS Document 添加了一个 xml。

用于内容绑定的 XML。

<employee>
<name></name>
</employee>

下面提到的方法用于将xml写入doc模板。该方法以 documentForm(result doc file)、xmlSchemaFilePath(created xml path)、templateForm(tempplete file) 作为参数。

 public String fillXMLBasedForm(String documentForm, String xmlSchemaFilePath, String templateForm)
        throws Exception {

    try {
        WordprocessingMLPackage wordMLPackage = Docx4J.load(new File(templateForm));
        FileInputStream xmlStream = new FileInputStream(xmlSchemaFilePath);
        Docx4J.bind(wordMLPackage, xmlStream, Docx4J.FLAG_BIND_INSERT_XML);
        Docx4J.save(wordMLPackage, new FileOutputStream(new File(documentForm)), Docx4J.FLAG_NONE);
    }
    catch(Exception e) {
        e.printStackTrace();
    }

    return documentForm;
}

一旦我打开生成的文档文件,就会出现“Word 发现无法读取的内容..”弹出窗口。一旦我作为受信任的文档继续,然后发现内容没有问题,因为为了测试目的,只写了一个字符串。

XML added via code. 

<employee>
<name>Vivek Singh</name>
</employee>

【问题讨论】:

标签: docx4j


【解决方案1】:

这是我用来解决这个问题的最低要求的 jars。

commons-compress-1.18
commons-io-2.6
docx4j-core-8.1.5
docx4j-JAXB-Internal-8.1.5
docx4j-openxml-objects-8.1.5
slf4j-api-1.7.26
xalan-interpretive-8.0.0
xalan-serializer-8.0.0

【讨论】: