使用binder来解析带有命名空间的xml时jaxb moxy的问题

时间:2013-03-20 11:37:07

标签: jaxb xml-namespaces moxy unmarshalling

我使用jaxb moxy从绑定器解组xml但是它给出了异常:在项目中找不到具有默认根元素bean的描述符。我还使用package-info.java来指定名称空间。

要解组的Xml文件 -

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.example.org/package">
</beans>

Beans.java -

@XmlRootElement(namespace="http://www.example.org/package")
public class Beans {

String name = "ss";

@XmlElement
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

package-info.java

@XmlSchema(
    namespace="http://www.example.org/package",
    elementFormDefault=XmlNsForm.QUALIFIED)
package com.jaxb.test;


import javax.xml.bind.annotation.*;

主要课程 -

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        File xml = new File(
                "D:\\eclipse-jee-indigo-SR2\beans.xml");
        Document document = db.parse(xml);

        JAXBContext jc = JAXBContext.newInstance(Beans.class);



        Binder<Node> binder = jc.createBinder();

        Beans customer = (Beans)   jc.createBinder().unmarshal(document);//throws exception

     //Beans customer = (Beans) jc.createUnmarshaller().unmarshal(xml);This works
    //Beans customer = (Beans) jc.createUnmarshaller().unmarshal(document);Throws same exception

异常 -

javax.xml.bind.UnmarshalException
- with linked exception:
[Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.4.1.v20121003-   ad44345): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element beans was not found in the project]
at  org.eclipse.persistence.jaxb.JAXBUnmarshaller.handleXMLMarshalException(JAXBUnmarshaller.java:1014)
at  org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:199)
at com.jaxb.test.JaxbTest.main(JaxbTest.java:43)

2 个答案:

答案 0 :(得分:1)

默认情况下,DocumentBuilderFactory不支持名称空间。这意味着您传递给MOXy的文档将不会按预期进行命名空间限定。您可以通过在代码中添加以下内容来解决此问题:

dbf.setNamespaceAware(true);

答案 1 :(得分:1)

解决了它。而不是使用package-info.java我使用了bindins.xml。

豆-bindings.xml -

<?xml version="1.0" encoding="UTF-8"?>
<xml-schema element-form-default="QUALIFIED" namespace="http://www.example.org/package">
    <xml-ns prefix="" namespace-uri="http://www.example.org/package" />
</xml-schema>

<java-types>
    <java-type name="Beans">
    <xml-root-element name="beans"/>
        <java-attributes>

        </java-attributes>
    </java-type>
</java-types>