从请求结果Schema中解析数据,且保证集合类型的数据不被覆盖。
import com.alibaba.fastjson.JSONObject;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.message.MessageElement;
import org.apache.axis.types.Schema;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static String parseXmlToJsonStr(Schema schema, String dataPath) {
String str = "";
String[] dataPaths = dataPath.split("\\.");
MessageElement[] msgele = schema.get_any();
//消息体信息,DataSet对象
MessageElement element = new MessageElement();
StringBuilder stringBuilder = new StringBuilder();
for (MessageElement messageElement : msgele) {
if (messageElement.getName() != null && messageElement.getName().equals(dataPaths[0])) {
stringBuilder.append(messageElement);
}
}
try {
element.setName("studentList");
element.setValue(stringBuilder.toString());
} catch (Exception e) {
LOG.error("-----------",e);
}
for (int i = 1; i < dataPaths.length - 1; i++) {
boolean flag = false;
for (Object o : element.getChildren()) {
MessageElement messageElement = (MessageElement) o;
if (messageElement.getName().equals(dataPaths[i])) {
element = messageElement;
flag = true;
break;
}
}
//消息体的字符串形式
String bodyStr = element.getValue().toString();
bodyStr = bodyStr.replaceAll("ns1:", "");
org.json.JSONObject xmlJSONObj = XML.toJSONObject(bodyStr);
LOG.info("======xmlJSONObj====={}",xmlJSONObj);
JSONObject jsonObject = JSONObject.parseObject(xmlJSONObj.toString());
LOG.info("======jsonObject====={}",xmlJSONObj);
// 递归根据dataPath的最后一层路径取数据
dataPath = dataPaths[dataPaths.length - 1];
LOG.info("======dataPath====={}",dataPath);
return jsonLoop(str, jsonObject, dataPath);
}
public static String jsonLoop(String str, Object object, String dataPath) {
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
if (dataPath.equalsIgnoreCase(entry.getKey())) {
str = entry.getValue().toString();
break;
} else {
str = jsonLoop(str, entry.getValue(), dataPath);
}
}
}
return str;
}