简体   繁体   English

使用JAXB解组列表

[英]Unmarshalling a list using JAXB

I know this is a beginner question, but I've been banging my head against a wall for two hours now trying to figure this out. 我知道这是一个初学者的问题,但是我已经将头撞在墙上两个小时了,试图解决这个问题。

I've got XML coming back from a REST service (Windows Azure Management API) that looks like the following: 我从看起来像以下的REST服务(Windows Azure管理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>

When I try to un-marshal it using JAXB, the list of services is always empty. 当我尝试使用JAXB取消封送处理时,服务列表始终为空。

I would like to avoid writing an XSD if possible (Microsoft doesn't provide one). 如果可能,我想避免编写XSD(Microsoft不提供XSD)。 Here is the JAXB code: 这是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());

And here are the Java classes: 这是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;
  }

}

Any help would be sincerely appreciated. 任何帮助将由衷的感谢。

@XmlRootElement 's namespace is not propagated to its children. @XmlRootElementnamespace不会传播到其子级。 You should specify the namespace explicitly: 您应该明确指定名称空间:

...
@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")
... 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM