使用 XPathResult [英] Using XPathResult

查看:13
本文介绍了使用 XPathResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 mozilla 开发者站点上找到了关于 XPathResult 的少量文档.列出的所有功能都重定向到主页,因此可能尚未记录它们.

I'm finding little documentation on XPathResult on the mozilla developper site. All functions listed redirect to the main page, so they're probably not documented yet.

var myFind;
myFind = document.evaluate(
    '/html/body/table[1]',
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null);

我正在寻找一种方法来提醒给定路径下的 HTML 树.

I'm looking for a way to alert the HTML tree that is under the path given.

使用 alert(myFind); 不起作用,它只会给出XPathResult".它下面只有一个 tbody 和一堆 tr 元素,我想在警报中将它们全部显示为 1 个字符串.

Using alert(myFind); doesn't work, it just gives "XPathResult". There's just a tbody and a bunch of tr elements beneath it, and I'd like to see them all in an alert as 1 string.

myFind 可以使用什么函数来做到这一点?

What function can myFind use to do this?

推荐答案

var myFind;
myFind = document.evaluate(
    '/html/body/table[1]',
    document,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null);

var node = myFind.singleNodeValue;

我使用 FIRST_ORDERED_NODE_TYPE 是因为您只查找单个表.singleNodeValue 允许您提取节点.

I'm using FIRST_ORDERED_NODE_TYPE because you're only looking for a single table. singleNodeValue lets you extract the node.

现在节点是一个普通的 HTML DOM Node.您可以像任何其他节点一样序列化它,例如使用 serializeToString:

Now node is a regular HTML DOM Node. You can serialize it the same way as any other node, e.g. with serializeToString:

new XMLSerializer().serializeToString(node)

您可能会发现使用 XPathXPathResult 很有帮助.

You may find Using XPath and XPathResult helpful.

这篇关于使用 XPathResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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