javaxmljaxbfxg

How do you get the unmarshaller in JAXB to ignore the XML root element name?


I am reading some XML data (FXG files if you are familiar with them).

Part of the data has varying tag names:

<varying_name1 scaleX="1.0046692" x="177.4" y="74.2"/>
<varying_name2  scaleX="1.0031128" x="171.9" y="118.9"/>    

I have created a class named Transforms to represent the data within the varying tag name segment. In my JAXB class to hold the data I have:

@XmlAnyElement(lax=true)    
@XmlJavaTypeAdapter(TransformAdapter.class)    
protected List<Transform> transforms;

In my Adapter, I attempt to unmarshal the data:

JAXBContext context = JAXBContext.newInstance(Transform.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Transform result = (Transform) unmarshaller.unmarshal(v);

However, my code throws an exception here because the root name on my element varies. It is not a constant. I get:

unexpected element (uri:"http://ns.adobe.com/fxg/2008", local:"m6_mc"). Expected elements are (none)

How can I get it to just unmarshal my data as if the root element had the name it expected?


Solution

  • By default a a JAXB (JSR-222) implementation will determine the class to unmarshal based on the root element. This is matched with metadata provided via an @XmlRootElement or @XmlElementDecl annotation.

    Alternately you one of the unmarshal methods that take a class parameter. This tells JAXB what class you wish to unmarshal to. The result of the unmarshal will be an instance of JAXBElement that in addition to the Java object will contain root element info in case you need it.

    JAXBContext context = JAXBContext.newInstance(Transform.class); 
    Unmarshaller unmarshaller = context.createUnmarshaller(); 
    Transform result = unmarshaller.unmarshal(v, Transform.class).getValue();