解决axis2 wsdl与请求soap报文中字段顺序不一致的问题:Unexpected subelement XXXX

时间:2022-03-03 15:58:32

axis2报错:org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement XXXX

因为wsimport命令生成的类是按照wsdl中字段的顺序进行校验的,所以当字段顺序不一致或者请求中的字段在wsdl不存在时,均会报此错误。

修改生成的类中的Factory.parse(...)方法,去除多数字段的校验,增加字段循环设值:

 // --------------------zhaigx20131202
                String fieldName = null;
                String fieldVal = null;
                QName qName = null;
                while (reader.isStartElement()) {
                    qName = reader.getName();
                    fieldName = qName.getLocalPart();
                    nillableValue = reader.getAttributeValue(
                            "http://www.w3.org/2001/XMLSchema-instance", "nil");
                    if ("true".equals(nillableValue)
                            || "1".equals(nillableValue)) {
                        throw new org.apache.axis2.databinding.ADBException(
                                "The element: " + fieldName
                                + "  cannot be null");
                    }
                    fieldVal = org.apache.axis2.databinding.utils.ConverterUtil
                            .convertToString(reader.getElementText());
                    MapperUtil.setPropertyVal(object, fieldName, fieldVal);

                    reader.next();// skip text
                    // skip other like space,tab
                    while (!reader.isStartElement() && !reader.isEndElement()) {
                        reader.next();
                    }
                    // move to next
                    if (reader.isEndElement()) {
                        reader.next();
                    }
                }
                // skip other like space,tab
                while (!reader.isStartElement() && !reader.isEndElement()) {
                    reader.next();
                }

                // --------------------end


 public static void setPropertyVal(Object dest, String key, Object val) {
        Class<?> clazz = dest.getClass();
        try {
            java.lang.reflect.Method setMethod = clazz.getMethod("set"
                    + StringUtils.capitalize(key), String.class);
            setMethod.invoke(dest, val);
        } catch (Exception e) {
            log.error("Error: {}={}", key, val);
        }
    }



soap报文中的对应类结尾标签可能需要增加reader.hashNext:

 while (!reader.isStartElement() && !reader.isEndElement()
                        && reader.hasNext()) {
                    reader.next();
                }