I've got a problem related to the unmarshalling process in a JAX-WS based WebService. In WSDL file there is an element defined as
<element name="quantity" nillable="true" type="int" />
In the related JAVA class it is defined as:
#XmlElement(name = "Quantity", required = true, type = Integer.class, nillable = true)
protected Integer quantity;
When an XML value for this element is the representation of a decimal number (3.4), the element is unmarshalled as a null Integer. No SOAPFault is generated and it's impossible to distinguish decimal values from null values inside the WebService.
Could it be a defect in JAXB implementation or I'm doing something wrong?
Could it be a defect in JAXB implementation or I'm doing something
wrong?
This is not a defect in the JAXB (JSR-222) implementation. It is a result of how the JAX-WS is configured to use JAXB. I will demonstrate below with an example.
Root
Below is a domain object with a field that matches the one from your question. I have remove the type=Integer.class from the #XmlElement annotation since it is redundant.
import javax.xml.bind.annotation.*;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Root {
#XmlElement(name = "Quantity", required = true, nillable = true)
protected Integer quantity;
}
Demo
JAXB offers the ability to set a ValidationEventHandler on the Unmarshaller to give you some control over how unmarshal errors are handled.
import java.io.StringReader;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler() {
#Override
public boolean handleEvent(ValidationEvent event) {
System.out.println(event.getMessage());
return true;
}
});
StringReader xml = new StringReader("<root><Quantity>3.4</Quantity></root>");
Root root = (Root) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
Output
In the expert group we decided that invalid element data is common and that JAXB should not fail out every time this is encountered, but you can see that a ValidationEvent is raised.
Not a number: 3.4
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<Quantity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</root>
Update Demo
If we update the ValidationEventHandler to indicate that we do not wish to continue the unmarshal when a ValidationEvent is raised we can make the following change.
#Override
public boolean handleEvent(ValidationEvent event) {
System.out.println(event.getMessage());
return false;
}
Updated Output
And now the following output occurs.
Not a number: 3.4
Exception in thread "main" javax.xml.bind.UnmarshalException: Not a number: 3.4
- with linked exception:
[java.lang.NumberFormatException: Not a number: 3.4]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:647)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleError(UnmarshallingContext.java:676)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleError(UnmarshallingContext.java:672)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.handleParseConversionException(Loader.java:256)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.LeafPropertyLoader.text(LeafPropertyLoader.java:54)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.text(UnmarshallingContext.java:499)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.processText(SAXConnector.java:166)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.endElement(SAXConnector.java:139)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1742)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2900)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:489)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:203)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:175)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:214)
at forum14741140.Demo.main(Demo.java:22)
Caused by: java.lang.NumberFormatException: Not a number: 3.4
at com.sun.xml.internal.bind.DatatypeConverterImpl._parseInt(DatatypeConverterImpl.java:101)
at com.sun.xml.internal.bind.v2.model.impl.RuntimeBuiltinLeafInfoImpl$17.parse(RuntimeBuiltinLeafInfoImpl.java:713)
at com.sun.xml.internal.bind.v2.model.impl.RuntimeBuiltinLeafInfoImpl$17.parse(RuntimeBuiltinLeafInfoImpl.java:711)
at com.sun.xml.internal.bind.v2.runtime.reflect.TransducedAccessor$CompositeTransducedAccessorImpl.parse(TransducedAccessor.java:232)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.LeafPropertyLoader.text(LeafPropertyLoader.java:50)
... 19 more
I answered this question in : https://stackoverflow.com/a/30617814/3632201
I have been struggling with this issue during the last week and finally i have managed a working solution. The trick is that JAXB looks for the methods beforeUnmarshal and afterUnmarshal in the object annotated with #XmlRootElement.
..
#XmlRootElement(name="MSEPObtenerPolizaFechaDTO")
#XmlAccessorType(XmlAccessType.FIELD)
public class MSEPObtenerPolizaFechaDTO implements Serializable {
..
public void beforeUnmarshal(Unmarshaller unmarshaller, Object parent) throws JAXBException, IOException, SAXException {
unmarshaller.setSchema(Utils.getSchemaFromContext(this.getClass()));
unmarshaller.setEventHandler(new CustomEventHandler());
}
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) throws JAXBException {
unmarshaller.setSchema(null);
unmarshaller.setEventHandler(null);
}
Using this ValidationEventHandler:
public class CustomEventHandler implements ValidationEventHandler{
#Override
public boolean handleEvent(ValidationEvent event) {
if (event.getSeverity() == event.ERROR ||
event.getSeverity() == event.FATAL_ERROR)
{
ValidationEventLocator locator = event.getLocator();
throw new RuntimeException(event.getMessage(), event.getLinkedException());
}
return true;
}
}
}
And this is the metodh getSchemaFromContext created in your Utility class:
#SuppressWarnings("unchecked")
public static Schema getSchemaFromContext(Class clazz) throws JAXBException, IOException, SAXException{
JAXBContext jc = JAXBContext.newInstance(clazz);
final List<ByteArrayOutputStream> outs = new ArrayList<ByteArrayOutputStream>();
jc.generateSchema(new SchemaOutputResolver(){
#Override
public Result createOutput(String namespaceUri,
String suggestedFileName) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
outs.add(out);
StreamResult streamResult = new StreamResult(out);
streamResult.setSystemId("");
return streamResult;
}
});
StreamSource[] sources = new StreamSource[outs.size()];
for (int i = 0; i < outs.size(); i++) {
ByteArrayOutputStream out = outs.get(i);
sources[i] = new StreamSource(new ByteArrayInputStream(out.toByteArray()), "");
}
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
return sf.newSchema(sources);
}
Related
I unmarshal the Document to object as below.
Before that, when parsing XML, use setUserData to store location information for each element.
class MyJaxbAdapter extends XmlAdapter<Object, SubObject> {}
#Override
public UnattendComponent unmarshal(Object v) throws Exception {
Node node = (Node) v; // ElementNSImpl; It's probably a newly created object. Because It is different from the document object given by ownerDocument as SAXSource.
node.getUserData(...) // return NULL
}
}
Document document = ...;
unmarshaller.setAdapter(new MyJaxbAdapter());
MyXMLObject object = unmarshaller.unmarshal(new DOMSource(document), MyXMLObject.class).getValue();
But I can't get UserData inside XmlAdapter's unmarshal method. Is there any way to persist UserData?
Locator information is stored in the properties of Element as shown below.
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
Element el = document.createElementNS(usedNamespaceUri, qName);
// ...
el.setUserData(
ElementUserData.class.getName(),
ElementUserData.builder()
.lineNumber(locator.getLineNumber())
.columnNumber(locator.getColumnNumber())
.build(),
null);
}
I need the Locator information (UserData) stored by the above code in the unmarshal of the XmlAdapter.
However, there is no userdata in the node passed as an argument to unmarshal .
Sample Code:
https://github.com/joseph-jclab/jaxb-question-01
Not entirely sure if this is something you are looking for but providing it as a reference so you might get some idea to proceed further:
Sample XML:
<root>
<name>Batman</name>
<year>2008</year>
</root>
Root.class:
#XmlRootElement(name = "root")
#Data
#XmlAccessorType(XmlAccessType.FIELD)
public class Root {
private String name;
private String year;
#XmlJavaTypeAdapter(CustomAdapter.class)
private String after;
private void afterUnmarshal(Unmarshaller m, Object parent) {
after = name;
}
}
CustomAdapter.class:
public class CustomAdapter extends XmlAdapter<String, String> {
#Override
public String unmarshal(String v) throws Exception {
System.out.println("Within Unmarshal : " + v);
return null;
}
#Override
public String marshal(String v) throws Exception {
System.out.println("Within Marshal : " + v);
return null;
}
}
SampleMain.class:
public class SampleMain {
public static void main(String[] args) throws XMLStreamException, JAXBException {
final InputStream inputStream = Unmarshalling.class.getClassLoader().getResourceAsStream("sample.xml");
final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
final Unmarshaller unmarshaller = JAXBContext.newInstance(Root.class).createUnmarshaller();
unmarshaller.setAdapter(new CustomAdapter());
final Root root = unmarshaller.unmarshal(xmlStreamReader, Root.class).getValue();
System.out.println(root.toString());
Marshaller marshaller = JAXBContext.newInstance(Root.class).createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(root, System.out);
}
}
Output:
Root(name=Batman, year=2008, after=Batman)
Within Marshal : Batman
<root>
<name>Batman</name>
<year>2008</year>
</root>
I am trying to learn JAXB. I created sample as below, but during unmarshalling i am getting exception. My files are below. Can you help me to resolve?
AddRequest.java:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "AddRequest", namespace = "http://www.example.org/AddRequest", propOrder = {
"first",
"sec",
"any"
})
public class AddRequest {
#XmlElement(name = "First")
protected int first;
#XmlElement(name = "Sec")
protected int sec;
#XmlAnyElement(lax = true)
protected List<Object> any;
}
ObjectFactory.java
#XmlRegistry
public class ObjectFactory {
private final static QName _AddRequest_QNAME = new QName("http://www.example.org/AddRequest", "AddRequest");
public ObjectFactory() {
}
public AddRequest createAddRequest() {
return new AddRequest();
}
#XmlElementDecl(namespace = "http://www.example.org/AddRequest", name = "AddRequest")
public JAXBElement<AddRequest> createAddRequest(AddRequest value) {
return new JAXBElement<AddRequest>(_AddRequest_QNAME, AddRequest.class, null, value);
}
}
package-info.java
#javax.xml.bind.annotation.XmlSchema(namespace = "http://www.example.org/AddRequest", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.example.addrequest;
Main.java
try {
File file = new File("C:\\Users\\nbkyooh\\IBM\\rationalsdp\\workspace\\Sample\\resource\\AddRequest.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(org.example.addrequest.AddRequest.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
jaxbUnmarshaller.unmarshal(file);
} catch (JAXBException e) {
e.printStackTrace();
}
AddRequest.xml
<?xml version="1.0" encoding="UTF-8"?>
<tns:AddRequest xmlns:tns="http://www.example.org/AddRequest" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/AddRequest AddRequest.xsd ">
<tns:First>0</tns:First>
<tns:Sec>0</tns:Sec>
</tns:AddRequest>
I am getting exception as below, what i have done wrong. I used all the generated files.
javax.xml.bind.UnmarshalException: Unexpected element "{http://www.example.org/AddRequest}AddRequest". Expected elements are "".
at com.ibm.xml.xlxp2.jaxb.msg.JAXBMessageProvider.throwUnmarshalExceptionWrapper(JAXBMessageProvider.java:93)
at com.ibm.xml.xlxp2.jaxb.unmarshal.impl.DeserializationContext.handleSkippedRootElementEvent(DeserializationContext.java:318)
at com.ibm.xml.xlxp2.jaxb.unmarshal.impl.JAXBDocumentScanner.produceRootElementEvent(JAXBDocumentScanner.java:189)
try this:
try {
FileInputStream inputStream = new FileInputStream(new File("your file"));
AddRequest req = JAXB.unmarshal(inputStream, AddRequest.class);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
In your use case you have define the root element information leveraging the #XmlElementDecl annotation on a ObjectFactory class annotated with #XmlRegistry (see: http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html). Since the class annotated with #XmlRegistry can be called anything and JAXB doesn't do package scanning you need to include your ObjectFactory as one of the classes passed in to bootstrap the JAXBContext.
JAXBContext.newInstance(AddRequest.class, ObjectFactory.class);
Since the ObjectFactory class references AddRequest you could simplify this down to:
JAXBContext.newInstance(ObjectFactory.class);
I'm trying to inject JAXB annotation at runtime using Javassist. I have written following code:
public class AssistAnnotationInjector {
public static void addAnnotationRunTime(String className, String fieldName) throws NotFoundException, CannotCompileException, IOException, ClassNotFoundException{
CtClass ctClass = ClassPool.getDefault().get(className);
ClassFile ccFile = ctClass.getClassFile();
ConstPool constPool = ccFile.getConstPool();
AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
Annotation annot = new Annotation("javax.xml.bind.annotation.XmlTransient",constPool);
attr.addAnnotation(annot);
CtField field = ctClass.getDeclaredField(fieldName);
field.getFieldInfo().addAttribute(attr);
System.out.println(field.getAnnotation(XmlTransient.class));
ccFile.setVersionToJava5();
ctClass.writeFile();
}
public static void main (String args[]) throws CannotCompileException, NotFoundException, IOException, SecurityException, NoSuchMethodException, ClassNotFoundException, JAXBException, NoSuchFieldException{
Person<Student> p = new Person<Student>();
p.setName("XYZ");
Student s = new Student();
s.setName("ABC");
s.setId("239423");
p.setPayload(s);
addAnnotationRunTime("RuntimeAnnotation.Person", "name");
Field f = p.getClass().getDeclaredField("name");
System.out.println(f.getAnnotation(XmlTransient.class));
JAXBContext context = JAXBContext.newInstance(p.getClass());
Marshaller mr = context.createMarshaller();
mr.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
mr.marshal(p, System.out);
}
}
And Person.java class is:
#XmlRootElement(name="Person")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlSeeAlso({Student.class})
public class Person <T>{
private T payload;
private String name;
public void setPayload(T payload){
this.payload = payload;
}
public T getPayload(){
return payload;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
In AssistAnnotationInjector.java, I am trying to add XmlTransient annotation to 'name' field. But the name field is still coming in marshalling output. Why is it so?
PS: marshal output is :
#javax.xml.bind.annotation.XmlTransient
null
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Person>
<payload xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="student">
<name>ABC</name>
<id>239423</id>
</payload>
**<name>XYZ</name>**
</Person>
name tag was not expected to present in output..
You basicaly have 2 options:
do the modification before you load the class. You can not use reflection in the normal way! One can try to use org.reflections with Maven plugin to pre-fetch classes. See here for more info.
use custom classloader to load the modified class. See here for more info.
After adding the attribute to the field you need to call ctClass.toClass() method,which freezes the class. After this you can check for the annotation.
My problem seems pretty simple, yet I was unable to find anything exactly like it on stackoverflow.
I'm using jaxb to marshall/unmarshall this object:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "")
#XmlRootElement(name = "root")
public class MyJaxbObject implements Serializable
{
#XmlElement(name = "DELETE")
#XmlJavaTypeAdapter(BooleanIntAdapter.class)
private Boolean delete;
#XmlElement(name = "message")
private String message;
constructors.. getters... setters...
}
My BooleanAdapter is a simple XmlAdapter<Integer, Boolean> that turns true/false to 1/0 and back.
Unmarshalling works, but marshalling does not. it always yeilds this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<DELETE xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.or/2001/XMLSchema" xsi:type="xs:boolean">true</DELETE>
<message>***DONE***</message>
</root>
When I change the xml element config to #XmlElement(name = "DELETE",type = Boolean.class) unmarshalling of the boolean fails and marshalling yields this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<DELETE xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:int">1</DELETE>
<message>***DONE***</message>
</root>
I put simple print messages in the marshal/unmarshal methods of the xml adapter and tried to marshal/unmarshal this kind of object.
I saw that without type declaration unmarshal method is called but marshal is not.
With the type declaration only marshal is called.
Help??
How can I marshal/unmarshal my Boolean to/from {1,0} and possibly get rid of the xsi:type in the marshalled xml?
Edit - this is the code i used to test marshal/unmarshal:
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
JAXBContext context = javax.xml.bind.JAXBContext.newInstance("my.package.classes");
Unmarshaller unmarshal = context.createUnmarshaller();
Marshaller marshal = context.createMarshaller();
marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
String str = "<root><DELETE>1</DELETE><message>***DONE***</message></root>";
DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
Document d = null;
d = builder.parse(new InputSource(new StringReader(str)));
MyJaxbObject myJaxUnmarsh = unmarshal.unmarshal(d.getFirstChild(), MyJaxbObject.class).getValue();
System.out.println(myJaxUnmarsh.getMessage() + " , " + myJaxUnmarsh.getDelete());
MyJaxbObject myJax = new MyJaxbObject();
myJax.setDelete(true);
myJax.setMessage("***DONE***");
marshal.marshal(myJax, System.out);
With the following implementation of BooleanIntAdapter:
BooleanIntAdapter
package forum9380680;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class BooleanIntAdapter extends XmlAdapter<Integer, Boolean> {
#Override
public Boolean unmarshal(Integer v) throws Exception {
return v.equals(1);
}
#Override
public Integer marshal(Boolean v) throws Exception {
if(v) {
return 1;
} else {
return 0;
}
}
}
Output
I get the following output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<DELETE>1</DELETE>
<message>***DONE***</message>
</root>
Below is the rest of the code I used:
Demo
package forum9380680;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(MyJaxbObject.class);
MyJaxbObject object = new MyJaxbObject();
object.setDelete(true);
object.setMessage("***DONE***");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(object, System.out);
}
}
MyJaxbObject
package forum9380680;
import java.io.Serializable;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "")
#XmlRootElement(name = "root")
public class MyJaxbObject implements Serializable
{
#XmlElement(name = "DELETE")
#XmlJavaTypeAdapter(BooleanIntAdapter.class)
private Boolean delete;
#XmlElement(name = "message")
private String message;
public Boolean getDelete() {
return delete;
}
public void setDelete(Boolean delete) {
this.delete = delete;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
found the problem:
CXF pom makes the project use jaxb-impl version 2.1.0.
Without CXF the project uses the JDK default which was 2.1.10 in my case.
see:
http://jaxb.java.net/guide/Which_JAXB_RI_is_included_in_which_JDK_.html
I added the following under dependency management to fix the problem
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.5</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
I have a problem.
I have the following XML:
<vehicles>
<Train name="train1" />
<Train name="train2" />
<Train name="train3" />
<Car name="car1" />
<Car name="car2" />
<Car name="car3" />
</vehicles>
I created an object:
#XmlRootElement(name="Car")
public class Car
{
private String name;
public Car() { super(); }
#XmlAttribute(name="name")
public String getName() { return name; }
public String setName(String name) { this.name = name; }
}
Now I am trying to use JAXB in order to generate Car objects from the XML calling the following method:
bindObjectsFromXml(file, Car.class);
public static <T> List<T> bindObjectsFromXml(File file, Class<T> klazz, String[] rootElementsNames) throws Exception
{
List<T> objects = new LinkedList<T>();
XMLStreamReader xmlStreamReader = getXMLStreamReader(file);
JAXBContext context = JAXBContext.newInstance(klazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
xmlStreamReader.nextTag();
for ( String rootElement : rootElementsNames ) // there might be more than one root that we want to skip
{
xmlStreamReader.require( XMLStreamConstants.START_ELEMENT, null, rootElement );
xmlStreamReader.nextTag();
}
while ( xmlStreamReader.getEventType() == XMLStreamConstants.START_ELEMENT )
{
JAXBElement<T> jaxbElement = unmarshaller.unmarshal(xmlStreamReader, klazz);
T klazzInstance = jaxbElement.getValue();
objects.add( klazzInstance );
if (xmlStreamReader.getEventType() == XMLStreamConstants.CHARACTERS)
{
xmlStreamReader.next();
}
}
return objects;
}
The problem is that I get Car object also from Train.
I don't understand why the unmarshaller ignores the #XmlRootElement(name="Car")?
Can you please help me with this?
Thank you very much in advance.
You need to ensure that your JAXBContext is aware of all the classes that you want to map to. In your example code you build the JAXBContext on Car.class so it will not be aware of Train.class. You will need to do the following:
JAXBContext jc = JAXBContext.newInstance(Car.class, Train.class);