users@jaxb.java.net

Re: Generating Java code from XML instance?

From: Aleksei Valikov <valikov_at_gmx.net>
Date: Wed, 9 Jul 2008 15:19:37 +0200

Hi.

> Sure.
>
> docx4j uses JAXB to marshal/unmarshal Microsoft's OpenXML.
>
> The following snippet of OpenXML is used to draw a horizontal line across
> the page (like HTML's <hr>):
>
> <w:p>
> <w:pPr>
> <w:pBdr>
> <w:bottom w:val="single" w:sz="6" w:space="1"
> w:color="auto" />
> </w:pBdr>
> </w:pPr>
> </w:p>
>
> I can produce that XML using the classes generated by XJC like this:
>
> org.docx4j.wml.ObjectFactory factory = new
> org.docx4j.wml.ObjectFactory();
> org.docx4j.wml.P p = factory.createP();
> org.docx4j.wml.PPr pPr = factory.createPPr();
> p.setPPr(pPr);
> org.docx4j.wml.PPrBase.PBdr bdr =
> factory.createPPrBasePBdr();
> org.docx4j.wml.CTBorder bottom =
> factory.createCTBorder();
> pPr.setPBdr(bdr);
> bdr.setBottom(bottom);
> bottom.setVal( org.docx4j.wml.STBorder.SINGLE );
> bottom.setSz( new java.math.BigInteger("6")); //yuck
> bottom.setSpace(new java.math.BigInteger("1"));
> bottom.setColor("auto");
>
> But it would be nice to say, "JAXB, here is the XML I'd like to generate;
> pls create some code for me", and get something like the above back.

Wow. :)

Please correct me if I misunderstand your task. I guess what you need
is to create JAXB structures (instances of schema-derived classes)
programmatically. And the idea is to give an example of XML, get the
code which produces this XML and use this code as reference/example to
create your own snippets.

I haven't tried this myself, but judging from the source code, what
could work is the following:

1. Implement your custom own com.sun.xml.bind.AccessorFactory which
produces field/property accessors. This custom factory should produce
accessors which, when being invoked, get/set values *as well as
log/create invocation code*.
2. Use com.sun.xml.bind.XmlAccessorFactory annotation (package or
class level) to configure your custom accessor factory for JAXB.

Seems quite uneasy, especially when you take things like adapters into
an account, but doable.

Bye.
/lexi