简体   繁体   中英

JAXB not unmarshalling xml any element to JAXBElement

I have a webservice call. In my response when I try to get the xml any element in to a JAXBElement it throws an error.

In the schema I have:

<xs:complexType name="InputType">
    <xs:annotation></xs:annotation>
    <xs:sequence>           
        <xs:element name="Id" type="xs:string" />
        <xs:any namespace="##any" processContents="lax" minOccurs="0" />
    </xs:sequence>
</xs:complexType>

The code I am using:

Object obj = inputType.getAny();
Object o = ((JAXBElement)obj).getValue(); 

This line throws the error: org.apache.xerces.dom.ElementNSImpl incompatible with javax.xml.bind.JAXBElement error in soap ui.

Why doesn't it covert to JAXBElement? How do I make it work?

If the property is annotated with the following the contents will be mapped as DOM nodes:

@XmlAnyElement

If the lax=true flag is set then known elements will be converted to domain objects:

@XmlAnyElement(lax=true)

For more information on @XmlAnyElement see:


UPDATE #1

With lax=true you can get a mix of domain objects and DOM nodes. The following is from the java docs:

When true

If true, when an element matches a property marked with XmlAnyElement is known to JAXBContext (for example, there's a class with XmlRootElement that has the same tag name, or there's XmlElementDecl that has the same tag name), the unmarshaller will eagerly unmarshal this element to the JAXB object, instead of unmarshalling it to DOM. Additionally, if the element is unknown but it has a known xsi:type, the unmarshaller eagerly unmarshals the element to a JAXBElement, with the unknown element name and the JAXBElement value is set to an instance of the JAXB mapping of the known xsi:type.

As a result, after the unmarshalling, the property can become heterogeneous; it can have both DOM nodes and some JAXB objects at the same time.


UPDATE #2

To ultimately solve the problem:

  1. Since it is possible for that property to contain a DOM node, your code should account for this possibility by doing some type checking.
  2. To reduce the amount of DOM nodes received you need to associate the possible root elements of those fragments with Java classes. This is done by annotating classes with @XmlRootElement(name="foo", namespace="bar"), or with @XmlElementDecl.

Check out my blog for an example:

validate your xml against your schema. that should be the first thing to be checked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM