I tried it, for example, like this:
- Code: Select all
- // load document that contains the target variable
 WordprocessingMLPackage mainPackage = WordprocessingMLPackage.load(new File(mainPath));
 VariablePrepare.prepare(mainPackage);
 MainDocumentPart mainDocPart = mainPackage.getMainDocumentPart();
 // load document that contains the content with which the target variable should be replaced
 WordprocessingMLPackage insertFromHerePackage = WordprocessingMLPackage.load(new File(insertFromHerePath));
 // get the XML of both documents
 String xmlMain = XmlUtils.marshaltoString(mainDocPart.getJaxbElement());
 String xmlToInsert = XmlUtils.marshaltoString(insertFromHerePackage.getMainDocumentPart().getJaxbElement());
 // map "target" variable to XML of second document
 HashMap<String, String> variables = new HashMap<>();
 variables.put("target", xmlToInsert);
 // create the new document from the XML of the first document and the mappings
 Document document = (Document) XmlUtils.unmarshallFromTemplate(xmlMain, variables);
 mainDocPart.setJaxbElement(document);
 Docx4J.save(mainPackage, new File(outPath));
Mapping a simple String like "Test" to the variable would work, but mapping it to the XML, like I do now, causes the following error messages:
- Code: Select all
- Caused by: javax.xml.bind.UnmarshalException: unexpected element (URI:"http://schemas.openxmlformats.org/wordprocessingml/2006/main", local:"document").
 Expected elements are <{ }text>
Two other errors are the same, but caused by com.sun.istack.internal.SAXParseException2 and the other by javax.xml.transform.TransformerException: com.sun.istack.internal.SAXParseException2.
Another error message says: org.docx4j.openpackaging.exceptions.Docx4JException: Cannot perform the transformation.
Using the method variableReplace causes the same errors and I have seen some old code that leads me to believe it may be possible with unmarshallFromTemplate.
I have also tried the Docx4J web app to generate XML from a Word file and I tried the generated Java code that uses a wml.ObjectFactory and marshaling that element to a string. Both approaches lead to the same errors.
Is it even possible to replace a variable with (Word!) XML content? Is there something I don't know about that may cause the errors? Please let me know if anything is unclear or other information is required.
Thank you for your time and help!


 News
 News Site map
 Site map SitemapIndex
 SitemapIndex RSS Feed
 RSS Feed