JAXB @XmlAnyElement example

Monday, June 7th, 2010

The problem

I was recently working on a JAXB centric app which was required to capture “arbitary” xml. e.g.

<a>
   <b></b>
   <c></c>
   <d>
       <!-- "Unknown" XML here -->
       <maybeE></maybeE>
       <maybeF></maybeF>
       <!-- etc etc -->
   <d/>
</a>

How could I ever capture the contents of if they could be “anything”?

The solution

@XmlRootElement(name="a")
public class A { 

   @XmlElement
   private String b; 

   @XmlElement
   private String c; 

   @XmlAnyElement
   private List<Element> content;
}

What’s going on?

The @XmlAnyElement annotation instructs JAXB to hoover up any elements which aren’t already annotated/associated with a field and store their DOM representation in:

private List content;

You could then do something like:

public String getContentAsString() throws Exception{
    StringBuilder builder = new StringBuilder();
    for (Node node: operations) {
        StringWriter writer = new StringWriter();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), new StreamResult(writer));
        builder.append(writer.toString());
    }
    return builder.toString();
}

To get the nested XML as String.

You can leave a response, or trackback from your own site.

Tags: , , ,
Posted in: Development, quick tips



Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>