xml的解析

xiaoxiao2021-02-28  146

后端返回的数据是xml格式的,以前做的项目都是json.稍微了解了下dom4j.

返回的数据

response = <?xml version="1.0" encoding="UTF-8" ?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><testJsonResponse xmlns="http://qcode.sia.org/"><result>{"%u4F60%u4F20%u5165%u7684abc":124,"%u4F60%u4F20%u5165%u7684def":"iikkkk"}</result></testJsonResponse></soap:Body></soap:Envelope>

Document document = DocumentHelper.parseText(response); //获取文档根节点 Element root = document.getRootElement(); //取各个节点下内容 Element Body = root.element("Body"); Element testJsonResponse = Body.element("testJsonResponse"); Element result = testJsonResponse.element("result"); resultInXML = result.getStringValue();

这个resultInXML就是result里的内容{"%u4F60%u4F20%u5165%u7684abc":124,"%u4F60%u4F20%u5165%u7684def":"iikkkk"}

通过URL解码

public static String unescape(String src) { StringBuffer tmp = new StringBuffer(); tmp.ensureCapacity(src.length()); int lastPos = 0, pos = 0; char ch; while (lastPos < src.length()) { pos = src.indexOf("%", lastPos); if (pos == lastPos) { if (src.charAt(pos + 1) == 'u') { ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16); tmp.append(ch); lastPos = pos + 6; } else { ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16); tmp.append(ch); lastPos = pos + 3; } } else if (pos == -1) { tmp.append(src.substring(lastPos)); lastPos = src.length(); } else { tmp.append(src.substring(lastPos, pos)); lastPos = pos; } } return tmp.toString(); } 得到需要的数据      {"你传入的abc":124,"你传入的def":"iikkkk"}

下个项目要用到,先写在这里记录一下.

转载请注明原文地址: https://www.6miu.com/read-23649.html

最新回复(0)