binding - EclipseLink MOXy : Bindings working with Unmarshaller but not with Binder

标签 binding jaxb eclipselink unmarshalling moxy

我使用相同的绑定(bind)配置进行解码,一次使用 Unmarshaler,一次使用 Binder。第一种方法工作正常,第二种方法抛出异常。原因是什么?

输入:

<?xml version="1.0" encoding="UTF-8"?>
<foo:root xmlns:foo="http://www.domain.org/foo">test</foo:root>

绑定(bind):

<?xml version="1.0"?>
<xml-bindings
 xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
 package-name="test">

<xml-schema element-form-default="QUALIFIED" namespace="http://www.domain.org/foo">
  <xml-ns prefix="foo" namespace-uri="http://www.domain.org/foo" />
</xml-schema>

<java-types>        
  <java-type name="Root">
    <xml-root-element name="root"/>
    <java-attributes>
      <xml-value java-attribute="text"/>
    </java-attributes>
  </java-type>
</java-types>

</xml-bindings>

类(class):

package test;

public class Root {

private String text;

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}
}

演示:

Map<String, Object> jaxbContextProperties = new HashMap<String, Object>(1);
jaxbContextProperties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "bindings.xml");
JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] { Root.class}, jaxbContextProperties);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Root root = (Root)unmarshaller.unmarshal(new File("input.xml"));

DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = documentBuilder.parse(new File("input.xml"));
Binder<Node> binder = jaxbContext.createBinder();
root = (Root) binder.unmarshal(document);

输出:

Exception in thread "main" javax.xml.bind.UnmarshalException - with linked exception:
[Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.5.0.v20130507- 3faac2b): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element foo:root was not found in the project]

最佳答案

EclipseLink JAXB (MOXy)没有问题您只需将代码更改为如下所示,以确保您的 DocumentBuilderFactory 能够识别命名空间:

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new File("input.xml"));

关于binding - EclipseLink MOXy : Bindings working with Unmarshaller but not with Binder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18001663/

相关文章:

c# - 如何将数据绑定(bind)到运行的内容?

java - 我应该在哪里验证 JavaFX 属性更改?

java - MOXy 的 xml-transient 声明是如何工作的?

java - @XmlElement注解中的sense类型元素是什么

date - 无法在 Eclipselink 上合并日期

c++ - Boost.Python 的私有(private)构造函数

c# - 将文本框绑定(bind)到字典

java - JAXB 和 HttpEntity

Java:最好将实体中的列表初始化为空列表或空列表

java - 如何在 eclipselink 中禁用缓存