简体   繁体   中英

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:

<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.

I would like to avoid writing an XSD if possible (Microsoft doesn't provide one). Here is the JAXB code:

  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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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