JAXB XmlJavaAdapter与@XmlAnyElement一起使用,而不与@XmlElement一起使用

时间:2019-05-02 10:21:00

标签: java jaxb

我有一个XmlAdapter类的实现,如下:

public class XMLSimpleElementAdapter extends XmlAdapter<Element, String> {

protected static final DocumentImpl doc=new DocumentImpl(true);

protected String elementName;
protected String nameSpace;

public XMLSimpleElementAdapter() {
    this("Description","https://www.proviseconsulting.com/ProcessDataModelDefinition");
}

public XMLSimpleElementAdapter(String elementName, String nameSpace) {

    this.elementName=elementName;
    this.nameSpace=nameSpace;

}//constructor closing

@Override
public Element marshal(String value) throws Exception {

    System.out.println("XMLSimpleElementAdapter -- marshal called");

    Element element=doc.createElement(elementName);
    element.setAttribute("xmlns", nameSpace);

    if(value!=null) {

        Node textValue=doc.createTextNode(value);
        element.appendChild(textValue);

    }//if closing

    return (Element)element;

}//marshal closing

@Override
public String unmarshal(Element element) throws Exception {

    System.out.println("XMLSimpleElementAdapter -- unmarshal called");

    String value="Some hard coded value";

    try {
    System.out.println("Element = "+element.getParentNode());
    }catch(Exception e) {e.printStackTrace();}
    Node textValue=element.getFirstChild();
    if(textValue!=null) {value=textValue.getNodeValue();}

    return value;

}//unmarshal closing
  }//class closing

我在类的属性上使用适配器:

@XmlAnyElement
//@XmlElement(name="Description",namespace="https://www.proviseconsulting.com/TriggerConfig")
@XmlJavaTypeAdapter(value = XMLSimpleElementAdapter.class)
protected String description;

其中XML是:<Description>This is the description of the configuration.</Description>

它工作得很好,我得到了价值。但是,如果我使用注释的“ @XmlElement”注释而不是@XmlAnyElement,则会出现以下错误:

    Exception in thread "main"   com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
org.w3c.dom.Element is an interface, and JAXB can't handle interfaces.
    this problem is related to the following location:
        at org.w3c.dom.Element
        at protected java.lang.String com.provise.wfm.trigger.config.TriggerConfigImpl.description
        at com.provise.wfm.trigger.config.TriggerConfigImpl

我缺少什么吗,JAXB可以使用@XmlAnyType而不是@XmlElement类型来处理org.W3c.dom.Element?

我正在将Sun / Oracle的JAXB实现与JDK 12(对J9使用AdOpenOpenJDK)

0 个答案:

没有答案