0

I'm using docx4j to read contents of a word document.

The core.xml has a description tag which I would like to modify in the documents I'm reading.

What is a best way to do this? Will I have to read the entire content of the document and create a new document using docx4j and change the description tag or is there a way to just change the description tag without modifying and/or reading->copying the content of the document?

Anthony
  • 33,838
  • 42
  • 169
  • 278

1 Answers1

0

See the sample DocProps.java at line 64 for how to fetch the core props part.

Then its something like:

    JAXBElement<SimpleLiteral> desc = coreProps.getDescription();
    SimpleLiteral literal = XmlUtils.unwrap(desc);
    List<String> contents = literal.getContent();

Then modify that list. As is typical with JAXB, its a live list, so your changes will be made immediately to the in-mem representation of the document.

Or you could create a new JAXBElement<SimpleLiteral> desc2, then coreProps.setDescription(desc2). That's what you'd do for a docx which doesn't have a dc:description already:

    org.docx4j.docProps.core.dc.elements.ObjectFactory dcFactory = new org.docx4j.docProps.core.dc.elements.ObjectFactory();
    SimpleLiteral literal = dcFactory.createSimpleLiteral();
    coreProps.setDescription(dcFactory.createDescription(literal));
    List<String> contents = literal.getContent();
    // populate contents ...

Then save the docx. The sample linked above does that.

JasonPlutext
  • 15,352
  • 4
  • 44
  • 84
  • This approach works find for documents that have a `description` tag in core.xml. However, there are certain documents (DOCX) which don't have a `description` tag. In those cases I get a NPE on `literal.getContent()`. Is there a way to set the description tag where it is non existent? – Anthony Aug 02 '13 at 04:25