[英]How to check an integer field in XML has string value in jaxb unmarshaling
使用JAXB解組時,我必須檢查xml中的整數字段中是否有字符串。
實現類:
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();
}
}
}
映射類:
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;
}
}
輸入XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="10">
<age>hello</age>
<name>Malik</name>
</student>
輸出:
Age : 0
Name : Malik
當我在整數字段中給出String值時,它的值為零。 我必須檢查如何檢查xml中具有非數字值的整數字段並引發錯誤。
JAXB
是一個便利類,其中包含JAXBContext
, Unmarshaller
和其他JAXB API庫,以使其更易於執行簡單的操作。 它的問題在於,它並沒有真正解決諸如驗證架構和性能問題之類的問題。 它將嘗試“盡力而為”,並忽略不匹配數據字段的問題,例如int
字段中的String
。
為了避免這種情況,您必須直接使用JAXB API,並在解編組過程中驗證模式。
我尚未測試此代碼,但是應該類似於以下內容:
JAXBContext jc = JAXBContext.newInstance(Student.class);
Unmarshaller u = jc.createUnmarshaller();
Student st = u.unmarshal(new File(xmlString));
您可能需要將解組官明確地交給學生,即:
Student st = (Student)u.unmarshal(new File(xmlString));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.