Java XPath:获取与查询匹配的所有元素

前端之家收集整理的这篇文章主要介绍了Java XPath:获取与查询匹配的所有元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想对这个 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>
...

我正在使用这段代码:@H_502_5@

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));

我期望得到什么:@H_502_5@

MasterModel
MassimaleModel
TravelModel

我得到什么@H_502_5@

MasterModel

似乎只有第一个元素被返回.如何获得与查询匹配的所有事件?@H_502_5@

解决方法

你会得到一个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相关文章