Page 1 of 1

Is there a way to map tags to HTML?

PostPosted: Wed Oct 12, 2011 4:27 am
by benpoole
Great library! Working well for me so far. I'm using the in-built functionality to map some "fields" (i.e. the ${TAG_NAME} syntax) in a template Word document to values derived from my underlying database. The technique I'm using for this is per the samples, i.e.

Code: Select all
Object obj = XmlUtils.unmarshallFromTemplate(xml, mappings);
XmlUtils.marshaltoString(obj, true);
content.setJaxbElement((org.docx4j.wml.Document) obj);


… and that works really well. What I want to do now is map some of my tag types to HTML. I've been using sample code for loading in HTML as an altChunk and that works but I can't get it to swap with the tags.

From what I can tell from unmarshalling the altChunk object, we get a load of XML starting with
Code: Select all
<w:altChunk r:id=.... />
Is there a simple way to then swap out the tag I've found (i.e. ${HTML}) with this generated XML in such a way that it will actually render?

I think the problem is that the code tries to insert the altChunk XML inside a w:t node, when it needs to actually replace the whole "parent" w:p node, but I'm a novice at this so could be wrong.

Any pointers gratefully received. I saw a post from last year about this from "vikrant" but they didn't appear to be having the same issue—duplicating his / her code just results in nothing being rendered at all for me:

docx-java-f6/can-i-insert-html-at-predefined-positions-in-my-template-t314.html#p945

Re: Is there a way to map tags to HTML?

PostPosted: Wed Oct 12, 2011 8:58 am
by jason
For the altChunk replacement - if I was just looking for one of these - I'd search the main document part (or header or footer) using XPath (provided I met the restrictions on its use - see Getting Started and the comments in MainDocumentPart).

If you need to do it at several places, use TraversalUtil.

In other words, unmarshallFromTemplate is not the right tool for this part of the job.

cheers .. Jason

Re: Is there a way to map tags to HTML?

PostPosted: Wed Oct 12, 2011 10:07 am
by benpoole
Thanks Jason

I came to the same conclusion and ended up writing some code which uses XPath. I've modified the "rich text" fields (i.e. those I wish to swap out with HTML from the underlying db system) to use a different tag name convention, and then I use XPath to locate and swap out these nodes (via the parent paragraph node). So far so good! I'll look at the TraversalUtil code too, that may be a better fit (there could be one rich text field, there could be five).