在XML

2016-08-31 61 views
0

JAXB編組額外的元素,我有以下Employee類,我需要以XML格式來表示在XML

員工:

@XmlRootElement(name="employee") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Employee { 

private int id; 
private String firstName; 
private String lastName; 
private int income; 

private Map<Integer,Employee> employeeMap=new HashMap<>();  
//getters and setters 
} 

編組代碼:

public class MarshallExample { 

public static void main(String[] args) throws JAXBException { 

    Map<Integer,Employee> empMap=new HashMap<>(); 

    Employee emp1=new Employee(); 
    emp1.setId(1); 
    emp1.setFirstName("aa"); 
    emp1.setLastName("bb"); 
    emp1.setIncome(1000); 

    Employee emp2=new Employee(); 
    emp2.setId(2); 
    emp2.setFirstName("xx"); 
    emp2.setLastName("yy"); 
    emp2.setIncome(2000); 

    empMap.put(1, emp1); 
    empMap.put(2, emp2); 

    Employee emp=new Employee(); 
    emp.setEmployeeMap(empMap); 

    JAXBContext jaxbContext=JAXBContext.newInstance(Employee.class); 
    Marshaller jaxbMarshaller=jaxbContext.createMarshaller(); 

    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
    jaxbMarshaller.marshal(emp, System.out); 


} 

}

XML輸出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<employee> 
<id>0</id> 
<income>0</income> 
<employeeMap> 
    <entry> 
     <key>1</key> 
     <value> 
      <id>1</id> 
      <firstName>aa</firstName> 
      <lastName>bb</lastName> 
      <income>1000</income> 
      <employeeMap/> 
     </value> 
    </entry> 
    <entry> 
     <key>2</key> 
     <value> 
      <id>2</id> 
      <firstName>xx</firstName> 
      <lastName>yy</lastName> 
      <income>2000</income> 
      <employeeMap/> 
     </value> 
    </entry> 
</employeeMap> 
</employee> 

無法確定爲什麼<id> 0 </id><income> 0 </income>元素出現在根元素內的輸出中,而不僅僅是兩個員工實例。

回答

0

這是因爲這是int值,不能是null。將其更改爲整數,它們不會再呈現。

@XmlRootElement(name="employee") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Employee { 

private Integer id; 
private String firstName; 
private String lastName; 
private Integer income; 

private Map<Integer,Employee> employeeMap=new HashMap<>();  
//getters and Setters 

} 
+0

感謝您的投入:) – abhi1489

+0

@ abhi1489不客氣 – Jens