似乎有几个关于这个问题的帮助主题,但我还没有找到一直困扰我的解决方案。
我必须使用下面的 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 一起使用