正则截取xml报文中的字段

原创
2020/10/30 16:49
阅读数 737
package com.example.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestController2 {
    public static void main(String[] args) throws ParseException {
        // inXml 为要截取的字符串
        String inXml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:ns6=\"http://www.chinatelecom.com/spr/\">"
                +"    <SOAP-ENV:Body>"
                +"          <ns6:User_Info_Response>"
                +"          <IsSuccess>0</IsSuccess>"
                +"          <ErrorDesc>success</ErrorDesc>"
                //  +"          <ErrorDesc>"<![CDATA[success]]></ErrorDesc>"
                +"       </ns6:User_Info_Response>"
                +"    </SOAP-ENV:Body>"
                +"    </SOAP-ENV:Envelope>";

        String context = null;
        // 截取<ErrorDesc> </ErrorDesc> 标签中的内容
        String xml = "ErrorDesc";
        context = regexLabel(inXml,"ErrorDesc");
        System.out.println(context);
    }

    // 截取内容的函数
    public static String regexLabel(String xml,String label) {
        String context = "";
        //正则表达式
        String regex = "<"+label+">(.*?)</"+label+">";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(xml);
        List<String> list = new ArrayList<String>();
        while(m.find()){
            int i = 1;
            list.add(m.group(i));
            i++;
        }
        if(list.size() > 0){
            context = list.get(0);
        }
        context=context.replace("<![CDATA[","");
        context=context.replace("]]>","");
        return context;
    }
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部