wangliangjin的gravatar头像
wangliangjin 2022-02-17 15:41:22
JAVA 获取xml字符串中数据

技术使用背景,系统之间对接传递的是xml格式的数据,这个时候需要我们解析xml

JAVA 获取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);
        }

    }

}

三、效果

JAVA 获取xml字符串中数据


打赏

已有1人打赏

最代码官方的gravatar头像
最近浏览
w2lijing2  LV10 2023年11月30日
opq221  LV3 2023年3月22日
klasjflewf  LV2 2023年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日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友