Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create objects from xml which has muitiple classes using JAXB?

Tags:

java

xml

jaxb

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 ?

like image 725
Peter Avatar asked Jun 07 '26 01:06

Peter


1 Answers

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.

like image 94
bdoughan Avatar answered Jun 09 '26 16:06

bdoughan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!