Jax-WS – 从请求XML中删除空标记
|
我正在尝试使用提供商公开的Web服务.提供者在他的结尾有一个严格的检查,请求xml不应该包含没有值的标签.
我正在使用Jax-WS.如果我没有在特定对象中设置值,则它将作为空标记发送,并且标记存在. PFB这个例子说明了我的问题. 客户端XML: <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:host="http://host.testing.webservice.com/">
<soapenv:Header/>
<soapenv:Body>
<host:testingMathod>
<arg0>
<PInfo>
<IAge>45</IAge>
<strName>Danny</strName>
</PInfo>
<strCorrId>NAGSEK</strCorrId>
<strIpAddress></strIpAddress>
</arg0>
</host:testingMathod>
</soapenv:Body>
</soapenv:Envelope>
在这里,没有给出IpAddress的值,因此发送了空标签. 因此,请告诉我们在删除请求xml中的空标记时需要做些什么. Handlerchain是同一个唯一的解决方案吗? 谢谢, 解决方法
注意:我是
EclipseLink JAXB (MOXy)领导者,也是
JAXB (JSR-222)专家组的成员.
默认情况下,MOXy与其他JAXB实现一样,不会为空值编组元素: > http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html 可能的问题 我相信strIpAddress属性不是null,但包含空字符串(“”)的值.这将导致写出空元素. 根 package forum11215485;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
String nullValue;
String emptyStringValue;
String stringValue;
}
演示 package forum11215485;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Root root = new Root();
root.nullValue = null;
root.emptyStringValue = "";
root.stringValue = "Hello World";
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
marshaller.marshal(root,System.out);
}
}
产量 注意没有为nullValue字段编组的元素,并且emptyStringValue字段被编组为空元素. <?xml version="1.0" encoding="UTF-8"?> <root> <emptyStringValue></emptyStringValue> <stringValue>Hello World</stringValue> </root> 解决方案#1 – 确保属性设置为null而不是“” 解决方案#2 – 编写一个将“”转换为null的XmlAdapter XmlAdapter是一种JAXB机制,允许将对象编组为另一个对象. StringAdapter 以下XmlAdapter将空字符串封送为null.这将导致它们不出现在XML表示中. package forum11215485;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class StringAdapter extends XmlAdapter<String,String> {
@Override
public String unmarshal(String v) throws Exception {
return v;
}
@Override
public String marshal(String v) throws Exception {
if(null == v || v.length() == 0) {
return null;
}
return v;
}
}
包信息 XmlAdapter使用@XmlJavaTypeAdapter注释挂钩.下面是一个在包级别挂钩的示例,以便它应用于包中String类型的字段/属性.有关更多信息,请参阅:http://blog.bdoughan.com/2012/02/jaxb-and-package-level-xmladapters.html @XmlJavaTypeAdapter(value=StringAdapter.class,type=String.class) package forum11215485; import javax.xml.bind.annotation.adapters.*; 产量 现在运行演示代码的输出如下: <?xml version="1.0" encoding="UTF-8"?> <root> <stringValue>Hello World</stringValue> </root> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
