使用JAXB解组列表

Mat*_*nit 5 java list jaxb azure

我知道这是一个初学者的问题,但是我现在一直在撞墙挡了两个小时,试图解决这个问题.

我从REST服务(Windows Azure Management API)返回XML,如下所示:

<HostedServices
  xmlns="http://schemas.microsoft.com/windowsazure"
  xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <HostedService>
    <Url>https://management.core.windows.net/XXXXX</Url>
    <ServiceName>foo</ServiceName>
  </HostedService>
  <HostedService>
    <Url>https://management.core.windows.net/XXXXX</Url>
    <ServiceName>bar</ServiceName>
  </HostedService>
</HostedServices>
Run Code Online (Sandbox Code Playgroud)

当我尝试使用JAXB解组它时,服务列表始终为空.

我想尽可能避免编写XSD(微软不提供).这是JAXB代码:

  JAXBContext context = JAXBContext.newInstance(HostedServices.class, HostedService.class);
  Unmarshaller unmarshaller = context.createUnmarshaller();
  HostedServices hostedServices = (HostedServices)unmarshaller.unmarshal(new StringReader(responseXML));

  // This is always 0:
  System.out.println(hostedServices.getHostedServices().size());
Run Code Online (Sandbox Code Playgroud)

以下是Java类:

@XmlRootElement(name="HostedServices", namespace="http://schemas.microsoft.com/windowsazure")
public class HostedServices
{
  private List<HostedService> m_hostedServices = new ArrayList<HostedService>();

  @XmlElement(name="HostedService")
  public List<HostedService> getHostedServices()
  {
    return m_hostedServices;
  }

  public void setHostedServices(List<HostedService> services)
  {
    m_hostedServices = services;
  }
}

@XmlType
public class HostedService
{
  private String m_url;
  private String m_name;

  @XmlElement(name="Url")
  public String getUrl()
  {
    return m_url;
  }

  public void setUrl(String url)
  {
    m_url = url;
  }

  @XmlElement(name="ServiceName")
  public String getServiceName()
  {
    return m_name;
  }

  public void setServiceName(String name)
  {
    m_name = name;
  }

}
Run Code Online (Sandbox Code Playgroud)

任何帮助将是真诚的感谢.

axt*_*avt 5

@XmlRootElementnamespace不会传播到其子.您应该明确指定命名空间:

...
@XmlElement(name="HostedService", namespace="http://schemas.microsoft.com/windowsazure") 
...
@XmlElement(name="Url", namespace="http://schemas.microsoft.com/windowsazure") 
...
@XmlElement(name="ServiceName", namespace="http://schemas.microsoft.com/windowsazure")
... 
Run Code Online (Sandbox Code Playgroud)

  • 还有一个`@ XmlSchema`包级注释.它为包中的所有类指定默认命名空间. (3认同)