在java中解组时发生xml错误
我有一个xml文件已经包含
***<?xml version=“1.0”encoding=“UTF-8”standalone=“是”&燃气轮机
<;客户 id="100">
<;年龄>;22</年龄>
<;名称>;纳文</名称>; </客户>**
我的POJO课程就是为了这个
公共类客户{
String name;
int age;
int id;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getId() {
return id;
}
}
我试图通过使用JAXB作为
File file = new File("sample.txt");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer);
但我也有例外
意外元素(uri:,本地:“客户”)。预期元素为(无)
请帮帮我
# 1 楼答案
可能有两个问题
1-纠正xml的格式,我可以在标签中看到空格,比如use,而不是<;使用>;最好使用下面的xml
2-并注释Jaxb类-使用下面的
# 2 楼答案
目前,类中没有足够的信息让JAXB知道基于根元素实例化哪个类。您可以执行以下操作之一:
Customer
类上添加@XmlRootElement
,以显式地将Customer
类映射到customer
根元素李>使用采用
unmarshal
参数的Class
方法:了解更多信息