docx4j

Is there something like setXML() for MainDocumentPart


The Class MainDocumentPart (or to be correct the inherited from JaxbXmlPart, but anyway...) of docx4j implements a method getXML() which returns a String with the XML code.

Now my question is: Is there also something that works the other way round - so that I have a given String containing the XML code and be able to set the MainDocmentPart accordingly?


Solution

  • Assuming MainDocumentPart mdp, an example would be:

        String openXML = "<w:document  xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" >"
                        + "<w:body>"
                                + "<w:p>"
                                        + "<w:r>"    
                                                + "<w:t>foo</w:t>"   
                                        + "</w:r>"    
                                + "</w:p>"
                        + "</w:body>"
                + "</w:document>";
    
    Document document = (Document)XmlUtils.unmarshalString(openXML);
    
    mdp.setContents(document );
    

    You can also add content at specific locations in the content tree using unmarshalString. To do that you typically get a reference to the parent object, by traversal or XPath usually.