在webservice调用的返回值中,为了传输方便,一般只有一个返回值.这返回值往往是xml或者json格式. 如果用java httpclient方式调用的话, 返回值将是完整的SOAP XML数据返回.如果想获取其中包含的真正的返回值,还需要解析这个xml, 然鹅....在用java自有的xml解析功能时, 在获取body节点(Element/Node)之后, 再获取body的内容时, 只能获取Text内容,并不包含子xml的标签.为解决这个问题我们需要使用到jdom这个jar包.下面举例说明获取xml内容的方式.
下载jdom(JDOM) 或者直接构建maven项目:
<!-- https://mvnrepository.com/artifact/jdom/jdom --> <dependency> <groupId>jdom</groupId> <artifactId>jdom</artifactId> <version>1.0</version> </dependency>
假如SOAP 返回值:
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"> <soapenv:Body> <root> <code>0</code> <message></message> <students> <student> <name>李二狗</name> <classroom>三班</classroom> <age>198</age> <sex>男</sex> </student> <student> <name>王丫蛋</name> <classroom>四(3)班</classroom> <age>19</age> <sex>女</sex> </student> </students> </root> </soapenv:Body> </soapenv:Envelope>
我们的目的是读取<ns:Body>内的root节点的所有xml内容如下:
解析的代码:
import java.io.ByteArrayOutputStream; import java.io.StringReader; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; import org.junit.jupiter.api.Test; class PenguinTest { @Test void test() { String soapresp = ""; soapresp = "<soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\">\r\n" + " <soapenv:Body>\r\n" + " <root>\r\n" + " <code>0</code>\r\n" + " <message></message>\r\n" + " <students>\r\n" + " <student>\r\n" + " <name>李二狗</name>\r\n" + " <classroom>三班</classroom>\r\n" + " <age>198</age>\r\n" + " <sex>男</sex>\r\n" + " </student>\r\n" + " <student>\r\n" + " <name>王丫蛋</name>\r\n" + " <classroom>四(3)班</classroom>\r\n" + " <age>19</age>\r\n" + " <sex>女</sex>\r\n" + " </student>\r\n" + " </students>\r\n" + " </root>\r\n" + " </soapenv:Body>\r\n" + "</soapenv:Envelope>"; SAXBuilder saxBuilder = new SAXBuilder(); StringReader reader = new StringReader(soapresp); Document build = null; try { build = saxBuilder.build(reader); // 读取root节点 Element body = (Element) build.getRootElement().getChildren().get(0); // ns:Body Element root = (Element) body.getChildren().get(0); // Element 转 XML String XMLOutputter xmlout = new XMLOutputter(); ByteArrayOutputStream bo = new ByteArrayOutputStream(); xmlout.output(root, bo); // 把Element 写入 ByteArrayOutputStream 中 String rootXml = bo.toString(); bo.close(); System.out.println(rootXml); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
得到的结果如下:
<root> <code>0</code> <message /> <students> <student> <name>李二狗</name> <classroom>三班</classroom> <age>198</age> <sex>男</sex> </student> <student> <name>王丫蛋</name> <classroom>四(3)班</classroom> <age>19</age> <sex>女</sex> </student> </students> </root>
标签:XML,xml,WebService,jdom,org,Element,子级,返回值,import From: https://www.cnblogs.com/equation/p/16783472.html