Search code examples
docx4j

Rich Text content control data binding with docx4j


Trying to create a data binding to custom XML part for a sdtBlock representing a rich text content control is not working because it creates a w:dataBinding tag in the resulting XML instead of a w15:dataBinding. Rich text content control require a w15 namespace uri.

I am creating the data binding directly in Java, not in an authoring tool, with this code:

org.docx4j.wml.CTDataBinding cTDataBinding = new CTDataBinding();

And there is no data binding class in org.docx4j.w15 package.

Is there any way to specify that a different namespace should be used for this instance when marshalling?


Solution

  • https://github.com/plutext/docx4j/blob/master/docx4j-openxml-objects/src/main/java/org/docx4j/w15/ObjectFactory.java#L232 contains:

    @XmlElementDecl(namespace = "http://schemas.microsoft.com/office/word/2012/wordml", name = "dataBinding")
    public JAXBElement<CTDataBinding> createDataBinding(CTDataBinding value) {
        return new JAXBElement<CTDataBinding>(_DataBinding_QNAME, CTDataBinding.class, null, value);
    }
    

    so you should be able to create what you want using the w15 ObjectFactory. For example:

        SdtPr sdtPr = new SdtPr();      
        JAXBElement<CTDataBinding> w15DataBinding = new org.docx4j.w15.ObjectFactory().createDataBinding(new CTDataBinding());      
        sdtPr.getRPrOrAliasOrLock().add(w15DataBinding);        
        System.out.println(XmlUtils.marshaltoString(sdtPr));
    

    produces (omitting some namespaces):

    <w:sdtPr xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" >
        <w15:dataBinding/>
    </w:sdtPr>