fab*_*ols 8 java xml wsdl jaxb 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了@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;
}
}
Run Code Online (Sandbox Code Playgroud)
在XML类中:
@XmlJavaTypeAdapter(value=AdaptorCDATA.class)
protected String dataRequest;
Run Code Online (Sandbox Code Playgroud)
我试图调试,但它从不踩到这个AdaptorCDATA
功能.
该wsimport
版本2.2.9
与jaxb-api
版本2.1
.
因此,正如@user1516873所建议的,我将代码移至 cxf,这样,运行良好。现在我使用“wsdl2java”来生成代码,并在我的项目中使用 cxf 生成 jar。
代码中有什么不同:
C数据拦截器
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
使用写入器和拦截器:
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);
Run Code Online (Sandbox Code Playgroud)
而且效果很完美!