I have an xml file already containing,
**< ?xml version="1.0" encoding="UTF-8" standalone="yes"?>
< customer id="100">
< age>22< /age>
< name>naveen< /name> < /customer>**
for which my POJO class is
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getId() {
return id;
}
}
I am trying to unmarshall this by using JAXB as,
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);
But I am getting an exception as
unexpected element (uri:"", local:"customer"). Expected elements are (none)
Please help me out.
Currently there isn't enough information in you class for JAXB to know which class to instantiate based on the root element. You can do one of the following:
@XmlRootElement
on your Customer
class to explicitly map the Customer
class to the customer
root element. Use an unmarshal
method that takes a Class
parameter:
JAXBElement<Customer> je = unmarshaller.unmarshal(source, Customer.class); Customer customer = je.getValue();
For More Information
There might be 2 issue
1 - Correct the format of xml, I could saw spaces in the tag like use instead of < use> better to use below xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
<age>22</age>
<name>naveen</name>
</customer>
2 - and annotate your Jaxb class - use the below
@XmlRootElement
public class Customer {
@XmlElement
String name;
@XmlElement
int age;
@XmlAttribute
int id;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getId() {
return id;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.