JAVA解析XML字符串简单方法代码案例
程序员文章站
2022-04-21 08:07:01
引入 dom4j 包 dom4j dom4j
引入 dom4j 包
<dependency> <groupid>dom4j</groupid> <artifactid>dom4j</artifactid> <version>1.6.1</version> </dependency>
比如阿里云视频转码服务的回调通知解析,代码如下:
import org.dom4j.document; import org.dom4j.documentexception; import org.dom4j.documenthelper; import org.dom4j.element; import java.util.iterator; public class domparser { public static void main(string[] args) { string strxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?> <notification xmlns=\"http://mns.aliyuncs.com/doc/v1/\"> <topicowner>1692545896541241</topicowner> <topicname>mytopic</topicname> <subscriber>1692545896541241</subscriber> <subscriptionname>bing-test3</subscriptionname> <messageid>c39fb8c345bbfba8-1-1687f6faadd-200000015</messageid> <messagemd5>caa1e9f5e9f854acd8297b100bf8ccf9</messagemd5> <message>{\"jobid\":\"2384a4d89b1d4f1e869559e2ff8c9fad\",\"requestid\":\"639d1d03-1557-4ad7-9ad7-691f02834516\",\"type\":\"transcode\",\"state\":\"success\",\"type\":\"transcode\",\"state\":\"success\",\"jobid\":\"2384a4d89b1d4f1e869559e2ff8c9fad\",\"requestid\":\"639d1d03-1557-4ad7-9ad7-691f02834516\"}</message> <publishtime>1548326251229</publishtime> </notification>"; document doc = null; try { doc = documenthelper.parsetext(strxml); } catch (documentexception e) { e.printstacktrace(); } element root = doc.getrootelement();// 指向根节点 iterator it = root.elementiterator(); while (it.hasnext()) { element element = (element) it.next();// 一个item节点 system.out.println(element.getname() + " : " + element.gettexttrim()); } } }
输出结果
topicowner : 1692545896541241 topicname : mytopic subscriber : 1692545896541241 subscriptionname : bing-test3 messageid : c39fb8c345bbfba8-1-1687f6faadd-200000015 messagemd5 : caa1e9f5e9f854acd8297b100bf8ccf9 message : {"jobid":"2384a4d89b1d4f1e869559e2ff8c9fad","requestid":"639d1d03-1557-4ad7-9ad7-691f02834516","type":"transcode","state":"success","type":"transcode","state":"success","jobid":"2384a4d89b1d4f1e869559e2ff8c9fad","requestid":"639d1d03-1557-4ad7-9ad7-691f02834516"} publishtime : 1548326251229
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 详解PHP显示MySQL数据的三种方法
下一篇: docker中安装宝塔面板