Reputation: 291
I have to check whether I have getting string in integer field in xml when unmarshaling using JAXB.
Implementation Class:
import java.io.IOException;
import javax.xml.bind.JAXB;
public class JAXBDemo {
public static void main(String[] args) throws IOException {
try {
String xmlString = "file:///c:/xml/stud.xml";
// unmarshal XML string to class
Student st = JAXB.unmarshal(xmlString, Student.class);
// prints
System.out.println("Age : "+st.getAge());
System.out.println("Name : "+st.getName());
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
Mapping Class :
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Student{
String name;
int age;
int id;
public String getName(){
return name;
}
@XmlElement
public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
@XmlElement
public void setAge(int age){
this.age = age;
}
public int getId(){
return id;
}
@XmlAttribute
public void setId(int id){
this.id = id;
}
}
Input XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="10">
<age>hello</age>
<name>Malik</name>
</student>
Output:
Age : 0
Name : Malik
when I give String value in integer field it gives as zero. I have to check how to check an integer field in xml having non numeric value and throw an error.
Upvotes: 1
Views: 1018
Reputation: 106
JAXB
is a convenience class that encompass JAXBContext
, Unmarshaller
and other JAXB API libraries to make it easier to perform simple operations.
The problem with it, that it's not really dealing with issues like validating the schemas and performance issues. it'll try to do a "best effort" and ignore issues for not matching data fields, such as String
in an int
field.
in order to circumvent that, you'll have to use the JAXB API directly, and validate the schema during the unmarshaling process.
I haven't tested this code, but it should be something similar to this:
JAXBContext jc = JAXBContext.newInstance(Student.class);
Unmarshaller u = jc.createUnmarshaller();
Student st = u.unmarshal(new File(xmlString));
you might need to explicitly cast the unmarshal to Student, i.e:
Student st = (Student)u.unmarshal(new File(xmlString));
Upvotes: 1