JAXB不按照注释生成XML(JDK 1.7)

时间:2014-09-19 12:02:01

标签: java xml jaxb

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;

    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;



    public class JavaToXMLDemo {
      public static void main(String[] args) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Employee.class);

    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Employee object = new Employee();
    object.setCode("CA");
    object.setName("Cath");
    object.setSalary(300);
    object.setProperties(new PropertiesMap());
    m.marshal(object, System.out);

  }
}

@XmlRootElement(name="Employee")
@XmlAccessorType(XmlAccessType.FIELD)
class Employee {
  private String code;

  @XmlElement(name = "Name")
  private String name;

  private int salary;

  @XmlElement(name = "Properties")
  protected PropertiesMap params;

  public String getCode() {
    return code;
  }

  public void setCode(String code) {
    this.code = code;
  }

  public PropertiesMap getProperties() {
      return params;
  }

  public void setProperties(PropertiesMap value) {
      this.params = value;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getSalary() {
    return salary;
  }

  public void setSalary(int population) {
    this.salary = population;
  }
}


  @XmlRootElement(name="Properties")
  class PropertiesMap<K,V> extends HashMap<K,V>
  {

  }

上面的代码使用JDK 1.6生成以下XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee>
    <code>CA</code>
    <Name>Cath</Name>
    <salary>300</salary>
    <Properties/>
</Employee>  

,这在JDK 1.7

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee>
    <code>CA</code>
    <Name>Cath</Name>
    <salary>300</salary>
    <params/>
</Employee>  

为什么Marshaller的行为有所不同?

1 个答案:

答案 0 :(得分:1)

您应该使用@XmlElementWrapper代替@XmlElement作为属性地图。

请参阅http://blog.bdoughan.com/2013/03/jaxb-and-javautilmap.html用例#2。