【发布时间】:2016-04-11 00:28:10
【问题描述】:
我是 jaxb 的新手,需要一些帮助。
我在尝试执行以下代码时得到空值。请有人指导我如何实现预期的输出。
我正在尝试解组的实际 XMl:
<?xml version="1.0" encoding="UTF-8"?>
<customer >
<cash xmlns:cash="uri:cash" >
<cash:no>10</cash:no>
<cash:name>naveen</cash:name>
<cash:age>27</cash:age>
<cash:phno>9176927613</cash:phno>
</cash>
</customer>
我正在使用的映射类:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@XmlRootElement(name="cash")
public class Cash {
private int no;
private String name;
private int age;
private Long phno;
public int getNo() {
return no;
}
@XmlElement(name="cash:no",nillable=true)
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
@XmlElement(name="cash:name",nillable=true)
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement(name="cash:age",nillable=true)
public void setAge(int age) {
this.age = age;
}
public Long getPhno() {
return phno;
}
@XmlElement(name="cash:phno",nillable=true)
public void setPhno(Long phno) {
this.phno = phno;
}
@Override
public String toString() {
return "Cash [no=" + no + ", name=" + name + ", age=" + age + ", phno="
+ phno + "]";
}
}
客户 DTO:
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="customer")
public class Customer {
private List<Cash> cash;
public List<Cash> getCash() {
return cash;
}
@XmlElement(name="cash")
public void setCash(List<Cash> cash) {
this.cash = cash;
}
@Override
public String toString() {
return "Customer [cash=" + cash + "]";
}
}
编组块:
File file = new File("cust.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer que= (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(que);
实际输出:Customer [cash=[Cash [no=0, name=null, age=0, phno=null]]]
预期的输出是实际的 XML 数据。
【问题讨论】:
-
下面是一个教程的链接。我不在我的电脑附近,看看可能出了什么问题。请比较您的代码,您应该缩小问题范围。 javacodegeeks.com/2013/02/jaxb-tutorial-getting-started.html