我试图为JAXB和java的Web服务做一些示例。在我的代码中,我想从XML文件中显示一些客户信息。我正在使用JAXB工具来读取/创建XML,并且我正在为客户对象分配值。当我尝试显示此客户类的值时,我得到空值。实际上,用于读取和显示客户信息的代码是可行的,但是当我在Web服务中使用它时,它无法正确显示。顺便说一句,我可以正确地在Web服务中创建XML,但阅读是个问题。这是我的代码:
实施
旧版本 @覆盖 public void displayXML(客户客户){
try {
File file = new File("C:\\Users\\ahmet.tanakol\\Desktop\\myfile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
customer = (Customer) jaxbUnmarshaller.unmarshal(file);
customer.setAge(customer.getAge());
customer.setId(customer.getId());
customer.setName(customer.getName());
} catch (JAXBException e) {
e.printStackTrace();
}
}
新版本(正确版本)
public String displayXML() {
String msg = "";
try {
File file = new File("C:\\Users\\ahmet.tanakol\\Desktop\\myfile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
msg += "Customer ID: " + customer.getId() + "Customer Age: " + customer.getAge() + "Customer Name: " + customer.getName();
} catch (JAXBException e) {
e.printStackTrace();
}
return msg;
}
运行程序时的结果
客户ID:100客户年龄:29客户名称:ahmet Hello World JAX-WS ahmet