WSDL客户端中的CDATA元素

时间:2016-06-20 12:27:15

标签: java xml jaxb wsdl wsimport

我正在做一个WSDL客户端,想知道如何将XML元素设置为CDATA。

我使用wsimport生成源代码,CDATA元素是请求XML的一部分。 这是请求的XML类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "dataRequest" }) 
@XmlRootElement(name = "ProcessTransaction")
public class ProcessTransaction {

    protected String dataRequest;

    public String getDataRequest() {
        return dataRequest;
    }

    public void setDataRequest(String value) {
        this.dataRequest = value;
    }  
} 

我已经尝试了@XmlAdapter,但它在输出中没有任何改变......

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class AdaptorCDATA extends XmlAdapter<String, String> {

    @Override
    public String marshal(String arg0) throws Exception {
        return "<![CDATA[" + arg0 + "]]>";
    }

    @Override
    public String unmarshal(String arg0) throws Exception {
        return arg0;
    }
}

在XML类中:

@XmlJavaTypeAdapter(value=AdaptorCDATA.class)
protected String dataRequest;

我尝试调试,但它永远不会踩到AdaptorCDATA函数。

wsimport版本为2.2.9jaxb-api版本为2.1

1 个答案:

答案 0 :(得分:1)

因此,正如@user1516873建议的那样,我将代码移动到cxf,并且使用它,运行良好。现在我正在使用&#34; wsdl2java&#34;在我的项目中生成代码和来自cxf的jar。

代码有什么不同:

<强> CdataInterceptor

$on('eventName', function(ev, data){})

<强> CDataContentWriter

import javax.xml.stream.XMLStreamWriter;

import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;

public class CdataInterceptor extends AbstractPhaseInterceptor<Message> {

    public CdataInterceptor() {
        super(Phase.MARSHAL);
    }

    public void handleMessage(Message message) {
        message.put("disable.outputstream.optimization", Boolean.TRUE);
        XMLStreamWriter writer = (XMLStreamWriter) message.getContent(XMLStreamWriter.class);
        if (writer != null && !(writer instanceof CDataContentWriter)) {
            message.setContent(XMLStreamWriter.class, new CDataContentWriter(writer));
        }
    }

    public void handleFault(Message messageParam) {
        System.out.println(messageParam);
    }
}

使用Writer和拦截器:

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.apache.cxf.staxutils.DelegatingXMLStreamWriter;

public class CDataContentWriter extends DelegatingXMLStreamWriter {

    public CDataContentWriter(XMLStreamWriter writer) {
        super(writer);
    }

    public void writeCharacters(String text) throws XMLStreamException {
        boolean useCData = text.contains("RequestGeneric");
        if (useCData) {
            super.writeCData(text);
        } else {
            super.writeCharacters(text);
        }
    }

    // optional 
    public void writeStartElement(String prefix, String local, String uri) throws XMLStreamException {
        super.writeStartElement(prefix, local, uri);
    }
}

它完美无缺!