从节点列表中按名称获取节点 [英] Get Node by Name from Nodelist

查看:65
本文介绍了从节点列表中按名称获取节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过 item(i)通过名称而不是通过索引获取节点,因为 Document 我正在阅读的内容不一定总是每次都在同一位置,但是节点的名称将始终相同。我正在尝试获取节点< reference>

I'm trying to get the node by its name instead of by its index via item(i) because the Document I'm reading won't always have the nodes in the same place every time but the names of the nodes will always be the same. I'm trying to get the node <reference>

到目前为止,我有:

System.out.println("Current Reference: " + 
    configurationDocument.getElementsByTagName("Parent").
        item(0).getChildNodes().item(0));

此问题是最后一个 item(0)总是得到错误的节点。如何通过名称( String )而不是通过 int 获取节点?

The problem with this is that the last item(0) always gets the wrong node. How do I get the node by name (String) instead of by int?

推荐答案

使用XPath获取您感兴趣的节点。

Use XPath to get the node that you are intrested in. Something like this:

XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression xpr = xpath.compile("//Parent/name-of-item/name-of-item");
System.out.println(xpr.evaluate(configurationDocument, XPathConstants.STRING));

这篇关于从节点列表中按名称获取节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆