开发者

Unmarshalling a list using JAXB

开发者 https://www.devze.com 2022-12-20 02:22 出处:网络
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 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>开发者_如何学Python;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")
... 
0

精彩评论

暂无评论...
验证码 换一张
取 消