2015-08-09 288 views
2

当我运行JAXBxmlToJava时LocationType集为空。任何机构都可以建议如何将xml的类型组件映射到Java的LocationType对象。 我有以下圆弧response.xml: -将Java对象映射到@XmlElement值

<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

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

当我测试你的代码中,Set<LocationType>null - 有两个LocationType,它出现,但他们typenull。我不确定这是否是您的问题。

当我改变了LocationType

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

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

它的工作。

+0

是的,你让我对“他们的类型字段为空”。我使用@ -XmlValue,但我得到以下异常。 com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:2个IllegalAnnotationExceptions的计数 如果某个类具有@ -XmlElement属性,则它不能具有@ -XmlValue属性。 \t这个问题涉及到以下位置: \t \t在私人java.lang.String中com.test.core.LocationType.type \t \t在com.test.core.LocationType \t \t在公共java.util中。设置com.leaks.impl.model.geo.location.AddressComponent.getLocationTypeSet() \t \t at com.leaks.impl.model.geo.location.AddressComponent –

+0

忽略“ - ”作为stackoverflow不允许我写@串。 –

+0

你有'AddressComponent'和'LocationType'单独的类文件吗?你是否从'LocationType'中删除了其他'@ XmlElement'? – Glorfindel