我正在做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.9
,jaxb-api
版本是2.1
。
因此,正如 @user1516873所建议的那样,我将代码移至cxf,因此运作良好。现在,我正在使用" WSDL2JAVA"来生成代码,而我的项目中的CXF罐子。
代码中有什么不同:
cdatainterceptor
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);
}
}
cdatacontentwriter
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);
}
}
使用作者和拦截器:
MyService wcf = new MyService(url, qName);
IMyService a = wcf.getBasicHttpBinding();
Client cxfClient = ClientProxy.getClient(a);
CdataInterceptor myInterceptor = new CdataInterceptor();
cxfClient.getInInterceptors().add(myInterceptor);
cxfClient.getOutInterceptors().add(myInterceptor);
它的工作完美!