4

I need to use <any>element in my xsd for scalability. So i used xsd as like below.

<complexType name="AddInput">
        <sequence>
            <element name="First" type="int"></element>
            <element name="Sec" type="int"></element>
            <any processContents="lax" namespace="##any" minOccurs="0" maxOccurs="unbounded"></any>
        </sequence>
    </complexType>

I have defined a complex object to place into the <any> placeholder, with ObjectFactory (@XMLRegistry, @XmlElementDecl) But still if i run below code, i am getting

org.apache.xerces.dom.ElementNSImpl

instead of JAXBElementObject. I searched in google, i see that JAXBContext should know about the schema. But i am not sure, how to make JAXBContext know my complex object. Any idea would be helpful.

        List<Object> elemList = (List<Object>)input.getAny();
        for(Object elem : elemList){
            System.out.println(elem.getClass());
        }
Manoj
  • 5,707
  • 19
  • 56
  • 86

2 Answers2

1

If you have a JAX-RS method like the following the JAXBContext used will be equivalent to making the following call JAXBContext.newInstance(Foo)

@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{id}")
public Foo read(@PathParam("id") long id) {
    return entityManager.find(Foo.class, id);
}

If you want the JAXBContext to be aware of all the classes you generated from the XML schema you can associate a JAXBContext with the domain object using a ContextResolver.

import java.io.*;
import java.util.*;     
import javax.ws.rs.Produces;
import javax.ws.rs.ext.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;

@Provider
@Produces(MediaType.APPLICATION_XML)
public class FooContextResolver implements ContextResolver<JAXBContext> {

    private JAXBContext jc;

    public FooContextResolver() {
        try {
            jc = JAXBContext.newInstance("com.example.foo");
        } catch(JAXBException e) {
            throw new RuntimeException(e);
        } 
    }

    public JAXBContext getContext(Class<?> clazz) {
        if(Foo.class == clazz) {
            return jc;
        }
        return null;
    }

} 

Example

Community
  • 1
  • 1
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • I am using RAD to generate the JAXB classes. I didnt use any external binding file. First of all how the xml got converted into object in CXF. How to use the context used by cxf to convert the object. I didnt understood from the link you have give. – Manoj Oct 08 '13 at 12:50
  • @Manoj - I have updated my answer to try an make it more clear. – bdoughan Oct 08 '13 at 13:17
  • sorry for my ignorance. I still couldnt get the point. When CXF databinding will know all the classes defined in the schema. Why it knows "AddInput" above alone and not the other one.? – Manoj Oct 08 '13 at 18:05
0

you need to set :

jaxb.additionalContextClasses

see : https://stackoverflow.com/a/55485843/1634131

Filip
  • 906
  • 3
  • 11
  • 33