Question

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.

Was it helpful?

Solution

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:

  1. Add @XmlRootElement on your Customer class to explicitly map the Customer class to the customer root element.
  2. Use an unmarshal method that takes a Class parameter:

    JAXBElement<Customer> je = unmarshaller.unmarshal(source, Customer.class);
    Customer customer = je.getValue();
    

For More Information

OTHER TIPS

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;
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top