Friday, 10 June 2016

XML : JAXB2 XmlAnyElement list Unmarshaller return null values

I am trying to unmarshall a simple configuration file from my classpath. This configuration file could contain a node <default_values> inside the <root> node with unlimited nodes with its values. A valid examples will be similar to the following:

  <root>     <default_values>       <host>HOST</host>       <port>5555</port>     </default_values>  </root>    

OR

  <root>     <default_values>       <host>127.0.0.1</host>       <other_property>789456</other_property>       <other_property_2>example</other_property_2>     </default_values>  </root>    

XSD:

  <xs:element name="default_values" minOccurs="0" maxOccurs="1">      <xs:complexType>        <xs:sequence>           <xs:any minOccurs="0" maxOccurs="unbounded" processContents="lax" />        </xs:sequence>      </xs:complexType>  </xs:element>    

POJO:

   @XmlAccessorType(XmlAccessType.FIELD)      @XmlType(name = "", propOrder = {          "any"      })      public static class DefaultValues {            @XmlAnyElement(lax = true)          protected List<Object> any;            public List<Object> getAny() {             if (any == null) {                any = new ArrayList<Object>();              }              return this.any;          }        }    

Unmarshalling:

  public static void main(String[] args) {            try {                File file = new File("./configuration.xml");              JAXBContext jaxbContext = JAXBContext.newInstance(MyRoot.class);                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();              MyRoot root= (MyRoot) jaxbUnmarshaller.unmarshal(file);                System.out.println("Default: " + root.getDefaultValues().getAny());            } catch (JAXBException e) {              e.printStackTrace();          }   }    

The result is similar to this:

  Default: [[host: null], [type: null]]    

I could see all the defined nodes but with null values for all them. Where is my error?

No comments:

Post a Comment