从xml文件中获取某个标签的值

时间:2024-03-28 10:17:40

从xml文件中获取某个标签的值 

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;

public class Test {

    /**
     *
     * @param xml形状的str串
     * @return Document 对象
     */
    public Document StringTOXml(String str) {

        StringBuilder sXML = new StringBuilder();
        sXML.append(str);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document doc = null;
        try {
            InputStream is = new ByteArrayInputStream(sXML.toString().getBytes("utf-8"));
            doc = dbf.newDocumentBuilder().parse(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }

    /**
     *
     * @param document
     * @return 某个节点的值 前提是需要知道xml格式,知道需要取的节点相对根节点所在位置
     */
    public String getNodeValue(Document document, String nodePaht) {
        XPathFactory xpfactory = XPathFactory.newInstance();
        XPath path = xpfactory.newXPath();
        String servInitrBrch = "";
        try {
            servInitrBrch = path.evaluate(nodePaht, document);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return servInitrBrch;
    }



    public static void main(String[] args) throws Throwable {
        String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<data>\r\n <message>\r\n <status>0</status>\r\n <value>处理成功</value>\r\n </message>\r\n <policeCheckInfos>\r\n <policeCheckInfo name=\"罗恩杰\" id=\"440105198307173914\">\r\n <message>\r\n <status>0</status>\r\n <value>查询成功</value>\r\n </message>\r\n <name desc=\"姓名\">罗恩杰</name>\r\n <identitycard desc=\"身份证号\">440105198307173914</identitycard>\r\n <compStatus desc=\"比对状态\">1</compStatus>\r\n <compResult desc=\"比对结果\">服务结果:库中无此号,请到户籍所在地进行核实!</compResult>\r\n <no desc=\"唯一标识\">40288945667c932001668b94e0cd6d66</no>\r\n </policeCheckInfo>\r\n </policeCheckInfos>\r\n</data>\r\n\r\n";
        Test t = new Test();
        // String ————》XML
        Document doc = t.StringTOXml(str);
        String nodePath = "/data/policeCheckInfos/policeCheckInfo/compResult";
        // getNodeValue
        String nodeValue = t.getNodeValue(doc, nodePath);
        System.out.println(nodeValue);

    }

}

 

相关文章