MMMMS
MMMMS

Reputation: 2201

JaxB - nested elements values are null

I am trying to convert XML to object using JAXB. Here is my code

<Root>
    <RName>jj</RName>
    <RID>55</RID>
    <Source>
        <Code ID="17">
           <Target Name="A" ID="20" StartAt=".01">
           </Target>

        </Code>
    </Source>
</Root>
@XmlRootElement(name = "Root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root { 
    public String RName;
    public int RID;
    public Source Source;
    
    //getter setter
}
@XmlRootElement(name = "Source")
@XmlAccessorType(XmlAccessType.FIELD)
public class Source {
    public Code Code;
    //getter setter
}
@XmlRootElement(name = "Code")
@XmlAccessorType(XmlAccessType.FIELD)
public class Code {
    public Target Target;
    public int ID;

}
@XmlRootElement(name = "Target")
@XmlAccessorType(XmlAccessType.FIELD)
public class Target {
    public String Name;
    public String ID;
    public String StartAt;
    //getter setter

}

JAXB :

File xmlFile = new File("Root.xml");
JAXBContext jaxbContext;
try
{
    jaxbContext = JAXBContext.newInstance(Root.class);              
 
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
 
    Root employee = (Root) jaxbUnmarshaller.unmarshal(xmlFile);
     
    System.out.println(employee);
}
catch (JAXBException e) 
{
    e.printStackTrace();
}

I can able to get RName,RID values, other values are null. Where Am I doing mistake ?

Upvotes: 0

Views: 648

Answers (1)

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

For the Java properties (Name, ID, StartAt) which are still null after unmarshalling, you missed to tell JAXB that these correspond to XML attributes (like StartAt="A"). By default JAXB assumes they correspond to XML elements (like <StartAt>.01</StartAt>).

You can fix your code by using the @XmlAttribute annotation. So for example, instead of

public String StartAt;

you need to write

@XmlAttribute(name = "StartAt")
public String StartAt;

And by the way: It is best practice to begin Java properties with a lowercase instead of an uppercase letter. So you could better write

@XmlAttribute(name = "StartAt")
public String startAt;

You still get the correct uppercased XML attribute name (here StartAt) by specifying name="StartAt" within the @XmlAttribute annotation.

The same is recommended for the Java properties corresponding to XML elements by using the @XmlElement annotation. like for example

@XmlElement(name = "RName")
public String rName;

Upvotes: 1

Related Questions