JAVA - 解析XML

时间:2016-09-27 22:13:42

标签: java xml

我有这个XML:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope>
    <soapenv:Body>
        <response>
            <note identifier="4719b11c-230e-4533-b1a5-76ac1dc69ef7" hash="956F3D94-A8B375ED-BA15739F-387B4F5E-75C6ED82" dat_prij="2016-09-27T23:06:20+02:00"/>
            <item uid="9f9cb5fb-75e6-4a2f-be55-faef9533d9ff-ff" active="true"/>
        </response>
    </soapenv:Body>
</soapenv:Envelope>

我需要解析 item uid ,在这种情况下它的值为“9f9cb5fb ...”,但我不知道如何解析Java标准节点。 谢谢你的建议。

编辑: 我尝试了这段代码,但没有工作:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(response));
    Document doc = builder.parse(is);

    Element root = doc.getDocumentElement();

    NodeList nList = doc.getElementsByTagName("soapenv:Envelope");
    NodeList body = nList.getElementsByTagName("soapenv:Body");
    NodeList resp = body.getElementsByTagName("response");


        Node node = nList.item("item");
        System.out.println("");    //Just a separator
        Element eElement = (Element) node;
        System.out.println(eElement.getAttribute("uid"));

1 个答案:

答案 0 :(得分:1)

使用DOM:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(response));
    Document doc = builder.parse(is);

    NodeList nList = doc.getElementsByTagName("item");
    Node namedItem = nList.item(0).getAttributes().getNamedItem("uid");
    System.out.println(namedItem.getNodeValue());

使用SAX:

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();

    DefaultHandler handler = new DefaultHandler() {

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if (qName.equals("item")) {
                System.out.println(attributes.getValue("uid"));
            }
        }
    };

    saxParser.parse(new InputSource(new StringReader(response)), handler);

您可能希望阅读有关XML,DOM和SAX的一些教程: https://docs.oracle.com/javase/tutorial/jaxp/dom/readingXML.html https://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html

或者你可以使用Regex和一些字符串替换:

    Pattern pattern = Pattern.compile("uid=\"[^\"]*\"");
    Matcher matcher = pattern.matcher(response);
    if(matcher.find()) {
        String attr = matcher.group();
        attr = attr.replace("\"", "");
        attr = attr.replace("uid=", "");
        System.out.println(attr);
    }

注意:

您的XML不是有效的SOAP消息。它缺少一些名称空间声明 - 没有声明soapenv前缀,并且您的元素和属性未定义。