有几个关于这个问题的帮助主题,但我还没有找到一直困扰我的解决方案。
我必须使用下面的 xml 结构:
<Customer xmlns="http://www.somedomain.com/customer-example">
<Name>David Brent</Name>
<Notes>Big time</Notes>
</Customer>
它还有其他字段,但即使使用这种最小的设置,我也无法让它工作。
我的pojo:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"name",
"notes"
})
@XmlRootElement(name = "Customer")
public class Customer {
@XmlElement(name = "Name", required = true)
public String name;
@XmlElement(name = "Notes", required = true)
public String notes;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
...
...
}
而客户:
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Customer customer = (Customer)unmarshaller.unmarshal(new File("Data.xml"));
System.out.println("Customer: "+customer.getName());
}
这将引发异常:
Exception in thread "main" javax.xml.bind.UnmarshalException:
unexpected element (uri:"", local:"root"). Expected elements are <{}Customer>
什么是本地:根???如果我尝试用另一种方式解析它
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource streamSource = new StreamSource("Data.xml");
JAXBElement<Customer> customer = (JAXBElement<Customer>).
unmarshaller.unmarshal(streamSource, Customer.class);
customer.getValue.getName(); //is null
这个问题与我的 xml 中的 xmlns 定义有关吗?
将 Netbeans 7.3.1 与 Java 1.7 结合使用 OpenJDK
是的,正如 Blaise 提到的,您缺少命名空间定义。
@XmlRootElement(name = "Customer", namespace="http://www.somedomain.com/customer-example")
基于异常的Data.xml
根元素是root
的,并且不像您期望的那样Customer
由命名空间限定。 要解决此问题,您可以像以前所做的那样使用采用Class
参数的unmarahal
方法。
您获得 name
属性null
的原因是您没有正确映射命名空间限定。 您可以使用包级别@XmlSchema
注释来执行此操作。 以下内容将帮助您映射到命名空间:
- http://blog.bdoughan.com/2010/08/jaxb-namespaces.html