我正在尝试使用提供商公开的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>
因此,请告诉我们在删除请求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>
解决方案#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>