Sure.
Its easiest when the original document.xml and the replacement have the same relationships.
In this simple case, you could either replace the JAXB element, or replace the MainDocumentPart.
Replacing the jaxbElement would be simpler. The problem with doing this is that there are some objects in the MainDocumentPart which are constructed when they are first requested (eg styleTree, propertyResolver), so if you've done something which has caused these to be created, you don't want to end up using these stale objects.
So better to replace the main document part. How about something like the following (untested):
- Code: Select all
// Keep existing relationships
RelationshipsPart rp = wordMLPackage1.getMainDocumentPart().getRelationshipsPart();
// We'll reuse the rel pointing to the MDP;
Relationship sourceRel = wordMLPackage1.getMainDocumentPart().getSourceRelationship();
// Create main document part
MainDocumentPart wordDocumentPart = new MainDocumentPart();
wordMLPackage1.getParts().put(wordDocumentPart);
wordDocumentPart.setPackage( wordMLPackage1 );
// Set shortcut to mdp
wordMLPackage1.setPartShortcut(wordDocumentPart, Namespaces.DOCUMENT);
// Reconnect the rels
wordDocumentPart.setSourceRelationship(sourceRel);
// Attach existing rels - this assumes existing rels are still relevant,
// and the new MDP doesn't contain any additional rel references
// or style references (not already in use in the existing doc)
wordDocumentPart.setRelationships(rp);
// TODO: setup part shortcuts on new MDP, if required
// See DocumentPart for how to do this
// Put the content in the part
wordDocumentPart.setJaxbElement(
(org.docx4j.wml.Document)XmlUtils.unmarshalString( yourDocumentXmlString ));