views:

291

answers:

1

Hi everyone. 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"&gt;
  <HostedService>
    <Url>https://management.core.windows.net/XXXXX&lt;/Url&gt;
    <ServiceName>foo</ServiceName>
  </HostedService>
  <HostedService>
    <Url>https://management.core.windows.net/XXXXX&lt;/Url&gt;
    <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.

+2  A: 

@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")
... 
axtavt
Thanks! That fixed the problem. But is this really the standard practice? The various JAXB samples I've seen online never seem to include the namespace.
Matt Solnit
There is also a `@XmlSchema` package-level annotation. It specifies the default namespace for all classes in the package.
axtavt