万能的XML解析方法,获取指定字段值

        上代码:

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
    
    public String handleXmlResponse(String response,String field) {
        if(StringUtils.isBlank(field)){
            return response;
        }
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new StringReader(response));
            Element root = document.getRootElement();
            return getFieldValue(root, field);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getFieldValue(Element element, String fieldName) {
        for (Iterator<Element> it = element.elementIterator(); it.hasNext();) {
            Element child = it.next();
            if (child.getName().equals(fieldName)) {
                return child.getText();
            } else {
                String fieldValue = getFieldValue(child, fieldName);
                if (fieldValue != null) {
                    return fieldValue;
                }
            }
        }
        return null;
    }

        此方法,便于我们处理xml的回报。