java dom xpath,Java:如何通过org.w3c.dom.document上的xpath字符串定位元素

How do you quickly locate element/elements via xpath string on a given org.w3c.dom.document? there seems to be no FindElementsByXpath() method. For example

/html/body/p/div[3]/a

I found that recursively iterating through all the child node levels to be quite slow when there are lot of elements of same name. Any suggestions?

I cannot use any parser or library, must work with w3c dom document only.

解决方案

Try this:

//obtain Document somehow, doesn't matter how

DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();

org.w3c.dom.Document doc = b.parse(new FileInputStream("page.html"));

//Evaluate XPath against Document itself

XPath xPath = XPathFactory.newInstance().newXPath();

NodeList nodes = (NodeList)xPath.evaluate("/html/body/p/div[3]/a",

doc.getDocumentElement(), XPathConstants.NODESET);

for (int i = 0; i < nodes.getLength(); ++i) {

Element e = (Element) nodes.item(i);

}

With the following page.html file:

link
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值