I am trying to create objects using binding data from xml file to classes which has generated from schema file xsd but it is giving null.
here is my xsd , from which I have generated my java classes :
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="people">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="employee"/>
<xsd:element ref="customer"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="employee">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref='name'/>
<xsd:element ref='country'/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name='name'>
<xsd:complexType>
<xsd:sequence>
<xsd:any namespace='http://www.w3.org/namespace/'/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name='country'>
<xsd:complexType>
<xsd:sequence>
<xsd:any namespace='http://www.w3.org/namespace/'/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="customer">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref='cname'/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name='cname'>
<xsd:complexType>
<xsd:sequence>
<xsd:any namespace='http://www.w3.org/namespace/'/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
My XML File:
<?xml version="1.0" encoding="UTF-8"?>
<people>
<employee>
<name>John</name>
<country>India</country>
</employee>
<customer>
<cname>steve</cname>
</customer>
</people>
and here my code which trying to bind xml data to java objects , but giving null:
File file = new File("D:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance("com.jaxb.xmlbinding");
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
People element = (People) jaxbUnmarshaller.unmarshal(file);
System.out.println(element.getEmployee().getName().getAny()); //giving null
could somebody please help me ….
means that element
namemay contain any XML element. No wonder you’re getting null, because XML contains text content.One solution may be to change schema to this:
(mind
mixed="true"). This way you’ll get:instead of:
and after unmarshalling, you’ll get:
EDIT: case when changing XSD is not an option
This is valid XML:
Then after unmarshalling you’ll get: