使用JAXB解组一个列表
问题描述:
我知道这是一个初学者问题,但我一直试图解决这个问题,一直在困扰我的头撞墙。使用JAXB解组一个列表
我有XML从REST服务(Windows Azure管理API),它看起来像下面回来:
<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>
当我尝试取消元帅使用JAXB它,服务的列表总是空的。
我想尽可能避免编写XSD(Microsoft不提供)。下面是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());
这里是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;
}
}
任何帮助将衷心感谢。
答
@XmlRootElement
的namespace
不传播给它的孩子。您应该明确指定名称空间:
...
@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")
...
谢谢!这解决了问题。但这真的是标准做法吗?我在网上看到的各种JAXB示例似乎没有包含名称空间。 – 2010-02-11 19:39:19
还有一个'@ XmlSchema'包级别注释。它为包中的所有类指定默认名称空间。 – axtavt 2010-02-11 19:56:22