通过使用Java和Xpath获取xml的所有属性

时间:2019-05-15 10:28:48

标签: java xml xslt xpath

我有以下xml:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://www.test.com/rest/v1" xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <child test="folder" id="2019-05-15-04.52.05.641880A01" />
   <child test="folder" id="2019-05-15-04.52.05.901880A02" />
</root>

我想通过使用Java代码和Xpath读取以上xml,检索子节点(即id="2019-05-15-04.52.05.641880A01" and id="2019-05-15-04.52.05.901880A02")的ID并将其存储到List中。我尝试使用以下Java代码:

        InputSource source = new InputSource(new StringReader(xml));
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document document = db.parse(source);
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        return xpath.evaluate(expression, document);

我使用以下Xpath和输入xml调用了上述方法:

*[local-name()='root']/*[local-name()='child']/@id

但是我只得到一个id,而不是所有ID。关于如何获取所有ID的任何想法?

1 个答案:

答案 0 :(得分:2)

我认为您的Xpath是正确的。您可以使用以下测试类进行验证。

package com.idsk.commons.xsl;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Test {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse("D://NewFile.xml");

        // Create XPath
        XPathFactory xpathfactory = XPathFactory.newInstance();
        XPath xpath = xpathfactory.newXPath();

        XPathExpression expr = xpath.compile("*[local-name()='root']/*[local-name()='child']/@id"); 

        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;

        List<String> ids = new ArrayList<>();
        for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue());
            ids.add(nodes.item(i).getNodeValue()); //store them into List
        }
    }
}

它将创建以下输出:

  

2019-05-15-04.52.05.6418418A01

     

2019-05-15-04.52.05.95.9880880A02