Search code examples
javaxmljaxbmarshallingunmarshalling

Wrong happens unmarshaling


I can not understand why the unmarshaling.

Here is my class:

@XmlRootElement(name = "privileges")
@XmlAccessorType(XmlAccessType.FIELD)
public  class Privilege {
    @XmlAttribute(name = "number_residents")
    private Integer numberResidents;
    @XmlAttribute(name = "value")
    private String value;
    @XmlElement(name = "privilege")
    private String privilage;

below getters, setters, equals and toString }

I'm trying to do unmarshalling.

 File file = new File( "response.xml");
                JAXBContext context = JAXBContext.newInstance(Privilege.class);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                Privilege privilege = (Privilege) unmarshaller.unmarshal(file);
                System.out.println(privilege);

But I always get:

Privilege{numberResidents=null, value='null', privilage='Test privilege'}

But in a file like this:

<?xml version="1.0" encoding="UTF-8"?>
<privileges>
    <privilege number_residents="3" value="bb2">Test privilege</privilege>
</privileges>

I need your help


Solution

  • Your mapping is incorrect.

    Try :

    @XmlRootElement(name = "privileges")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Privileges {
    
        @XmlElement(name="privilege")
        private Privilege privilege;
    
        //Getters and setters
    
    }
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Privilege{
    
        @XmlAttribute(name = "number_residents")
        private Integer numberResidents;
        @XmlAttribute(name = "value")
        private String value;
        @XmlValue
        private String privilege;
    
        //getters and setters
    
    }