wangliangjin
2022-02-17 15:41:22
JAVA 获取xml字符串中数据
技术使用背景,系统之间对接传递的是xml格式的数据,这个时候需要我们解析xml
一、导入依赖
<dependency> <groupId>org.dom4j</groupId> <artifactId>dom4j</artifactId> <version>2.1.1</version> </dependency>
二、核心代码
import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; /** * @author 王良进 * @ClassName test.java * @createTime 2021年11月19日 19:44:00 */ public class test { public static void main(String[] args) throws DocumentException { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tns=\"http://webservice/\"><soap:Body><TASK_CREATEResponse><success>true</success><data><taskId>222</taskId></data></TASK_CREATEResponse></soap:Body></soap:Envelope>"; Document xmlDocument = DocumentHelper.parseText(xml); if(xmlDocument!=null){ //获取根节点 Element rootElement = xmlDocument.getRootElement(); //显示根节点的名字 System.out.println(rootElement.getName()); //获取根节点下的直接子节点的个数和名字 Element e2 = rootElement.element("Body"); Element e3 = e2.element("TASK_CREATEResponse"); Element e4 = e3.element("data"); String success = e3.element("success").getText().trim(); String taskId = e4.element("taskId").getText().trim(); System.out.println(taskId); } } }
三、效果
评论

opq221 LV3
3月22日
klasjflewf LV2
1月28日
唐僧洗头爱飘柔 LV22
2022年11月1日
itlaolang LV5
2022年10月28日
aoaaoaa
2022年10月25日
暂无贡献等级
z6622513 LV3
2022年9月8日
yabyang LV1
2022年8月29日
zhangqqq
2022年8月22日
暂无贡献等级
heifenglei LV7
2022年8月3日
17558420274 LV15
2022年7月22日