Reputation: 185
I have xsd and xml file. first I have generated Java classes from xsd file ,that part has done and now I have to feed data into objects using xml ? I am using below code , but this is throwing JAXBException.
try {
File file = new File("D:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance("com.jaxb.generated");
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Employee empObj = (Employee) jaxbUnmarshaller.unmarshal(file);
System.out.println(empObj.getName());
} catch (JAXBException e) {
e.printStackTrace();
}
and here is my xml file which contains two classes :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Employee> <name>John</name> <salary>5000</salary> </Employee> <Customer> <name>Smith</name> </Customer>
could somebody help me ?
Upvotes: 3
Views: 791
Reputation: 149047
The XML document in your question is invalid. XML documents need to have a single root element. The first step would be to ensure that your XML document is valid against the XML schema you generated the classes from.
Upvotes: 3
Reputation: 10180
IMPORTANT
You've an error in your code. You skipped this step:
JAXBElement element = (JAXBElement) jaxbUnmarshaller.unmarshal(f);
Well, I've worked with JAXB a long time ago.
However what we used to to in such a sitatuation, was to define an top level element (in Java code or in xsd file) enclosing the other elements.
e.g.:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<People>
<Employee>
<name>John</name>
<salary>5000</salary>
</Employee>
<Customer>
<name>Smith</name>
</Customer>
</People>
Java will generate the classes Employee and Customer as children of People.
You could iterate through it in JAXB code in the following way:
try {
File file = new File("D:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance("com.jaxb.generated");
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
JAXBElement element = (JAXBElement) jaxbUnmarshaller.unmarshal(file);
People people = (People) element.getValue();
Employee employee = (Employee)people.getChildren().get(0); // the name of the getChildren() methodm may vary
Customer customer = (Customer)people.getChildren().get(1);
System.out.println(empObj.getName());
} catch (JAXBException e) {
e.printStackTrace();
}
You may also want to take a look at this similar question: iterate-through-the-elements-in-jaxb
Upvotes: 3