将Java对象映射到@XmlElement值

时间:2015-08-09 08:22:02

标签: java xml xml-parsing jaxb annotations

当我运行JAXBxmlToJava时,LocationType设置为null。任何人都可以建议如何将xml的类型组件映射到Java的LocationType对象。 我有以下arc-response.xml: -

<address_component>
   <long_name>BMC Colony</long_name>
   <short_name>BMC Colony</short_name>
   <type>neighborhood</type>
   <type>political</type>
  </address_component>

以下代码,AddressComponent: -

@XmlRootElement(name = "address_component")
public class AddressComponent {

    @XmlElement(name = "long_name")
    private String longName;
    @XmlElement(name = "short_name")
    private String shortName;
    @XmlElement(name = "type")
    private Set<LocationType> locationTypeSet;
    //Setter Getter
}

的locationType: -

@XmlRootElement(name="type")
public class LocationType {

    private Integer locationTypeId;
    @XmlElement(name = "type")
    private String type;
    private String status;
    //Setter Getter
}

JAXBxmlToJava.java:-

    public class JAXBxmlToJava {
    public static void main(String[] args) {
        try {
            File file = new File("arc-response.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(AddressComponent.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            AddressComponent geoResponse = (AddressComponent) jaxbUnmarshaller.unmarshal(file);
            System.out.println(geoResponse);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您需要@XmlValue将文本节点(例如“邻居”)映射到自定义类中的字段。

当我测试您的代码时,Set<LocationType>不是null - 其中有两个LocationType,但他们的 type字段 null。我不确定这是否就是你在问题中的意思。

当我将LocationType课程更改为

@XmlRootElement(name = "type")
public class LocationType {

    private Integer locationTypeId;
    @XmlValue
    private String type;
    private String status;
    // Setter Getter
}

它有效。