1

似乎有几个关于这个问题的帮助主题,但我还没有找到一直困扰我的解决方案。

我必须使用下面的 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 一起使用

4

2 回答 2

0

Data.xml基于异常的根元素root不受Customer您期望的命名空间的限制。为了解决这个问题,您可以像您所做的那样使用unmarahalClass参数的方法。

您获得nullname属性的原因是您没有正确映射命名空间限定。您可以使用包级别@XmlSchema注释来执行此操作。以下将帮助您映射到命名空间:

于 2013-10-14T14:38:41.493 回答
0

Yes as Blaise mentioned, you are lacking the namespace definition.

@XmlRootElement(name = "Customer", namespace="http://www.somedomain.com/customer-example")
于 2013-10-14T14:50:59.003 回答