Search code examples
xmljaxbjava-6

Not able to read read xml attribute using JaxB


I have one XML file which I am trying to load using JaxB.

<TABLE NAME="EMPLOYEE">
    <ROW>
        <EMP_ID>1002</EMP_ID>
        <EMP_NAME>Suraj</EMP_NAME>
        <EMP_DEPT_ID>3</EMP_DEPT_ID>
        <EMP_DES>SE</EMP_DES>
    </ROW>
    <ROW>
        <EMP_ID>1034</EMP_ID>
        <EMP_NAME>Birendra</EMP_NAME>
        <EMP_DEPT_ID>6</EMP_DEPT_ID>
        <EMP_DES>SSE</EMP_DES>
    </ROW>
</TABLE>

Alos created POJO for the same as follow

@XmlRootElement
public class EmpTable {
    private String NAME;
    private EmpRow ROW;


    public String getNAME() {
        return NAME;
    }
    @XmlAttribute
    public void setNAME(String nAME) {
        NAME = nAME;
    }

    public EmpRow getROW() {
        return ROW;
    }
    @XmlElement
    public void setROW(EmpRow rOW) {
        ROW = rOW;
    }


}

Similar for EmpRow too. Reading Xml by using following code

File file = new File("C:/Users/navnath.kumbhar/Desktop/ImportDataXml.xml");
EmpTable objEmpTable = JAXB.unmarshal(file, EmpTable.class);

Now the problem is I am able to read full object and it's data properly except NAME attribute of TABLE tag. Can any suggest me what is there any wrong implimentionation or anything else is required?


Solution

  • MAPPING TO XML ATTRIBUTES

    You should annotate your the NAME property as follows:

    @XmlAttribute(name="NAME")
    public void setNAME(String nAME) {
        NAME = nAME;
    }
    

    Although I would recommend using the following naming convention:

    @XmlAttribute(name="NAME")
    public void setName(String nAME) {
        NAME = nAME;
    }
    

    MAPPING THE ROOT ELEMENT

    Also it appears as though you should use the @XmlRootElement as follows.

    @XmlRootElement(name="TABLE")
    public class EmpTable {
    

    Although you would probably be better off just having a Table class:

    @XmlRootElement(name="TABLE")
    public class Table {
    

    JAXB RUNTIME

    The following is a single line of code, but is not very efficient,

    EmpTable objEmpTable = JAXB.unmarshal(file, EmpTable.class);
    

    Instead you should create a JAXBContext which is a thread safe initialized version of the mapping metadata from which marshallers and unmarshallers can be created.

    JAXBContext jc = JAXBContext.newInstance(EmpTable.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    EmpTable objEmpTable = (EmpTable) unmarshaller.unmarshal(file);