gpt4 book ai didi

java - 使用java和Xpath获取xml的所有属性

转载 作者:行者123 更新时间:2023-12-02 01:30:26 25 4
gpt4 key购买 nike

我有以下 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(即id =“2019-05-15-04.52.05.641880A01”和id =“2019-05” -15-04.52.05.901880A02") 并将它们存储到 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 吗?

最佳答案

我认为你的 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.641880A01

2019-05-15-04.52.05.901880A02

关于java - 使用java和Xpath获取xml的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56147158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com