gpt4 book ai didi

Java XPath : Get all the elements that match a query

转载 作者:搜寻专家 更新时间:2023-10-30 21:18:23 27 4
gpt4 key购买 nike

我想对此 XML 文件进行 XPath 查询(显示摘录):

<?xml version="1.0" encoding="UTF-8"?>
<!-- MetaDataAPI generated on: Friday, May 25, 2007 3:26:31 PM CEST -->
<Component xmlns="http://xml.sap.com/2002/10/metamodel/webdynpro" xmlns:IDX="urn:sap.com:WebDynpro.Component:2.0" mmRelease="6.30" mmVersion="2.0" mmTimestamp="1180099591892" name="MassimaleContr" package="com.bi.massimalecontr" masterLanguage="it">
...
<Component.UsedModels>
<Core.Reference package="com.test.test" name="MasterModel" type="Model"/>
<Core.Reference package="com.test.massimalecontr" name="MassimaleModel" type="Model"/>
<Core.Reference package="com.test.test" name="TravelModel" type="Model"/>
</Component.UsedModels>
...

我正在使用这段代码:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document document = builder.parse(new File("E:\\Test branch\\test.wdcomponent"));
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();

xpath.setNamespaceContext(new NamespaceContext() {
...(omitted)

System.out.println(xpath.evaluate(
"//d:Component/d:Component.UsedModels/d:Core.Reference/@name",
document));

我期望得到的:

MasterModel
MassimaleModel
TravelModel

我得到的:

MasterModel

好像只返回了第一个元素。我怎样才能得到与我的查询匹配的所有事件?

最佳答案

你会得到一个 NodeList 类型的项目

XPathExpression expr = xpath.compile("//Core.Reference");
NodeList list= (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
System.out.println(node.getTextContent());
// work with node

关于Java XPath : Get all the elements that match a query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10734847/

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