34

我正在寻找一个 XPath 库来查询 FF、IE、Opera 和 Safari 中的 XML 文档……但找不到。你见过吗?

4

12 回答 12

10

Google 刚刚发布了 Wicked Good XPath - 对 Cybozu Lab 著名的 JavaScript-XPath 的重写。

链接:https ://github.com/google/wicked-good-xpath

重写后的版本比原来的实现小 40%,快 30%。

于 2012-09-01T08:06:38.483 回答
5

Google 的 AJAXSLT开源项目非常符合规定的要求。

正如他们自己的描述所说:

“AJAXSLT 是JavaScript中 XSLT 的实现。因为 XSLT 使用 XPath,所以它也是 XPath 的实现,可以独立于 XSLT 使用。这种实现的优点是,它使 XSLT 在比本机提供的更多浏览器上统一可用,并且如有必要,它可以扩展到更多的浏览器 。AJAXSLT 对于积极争取其高级 Web 应用程序的跨浏览器兼容性的开发人员来说很有趣

更新:在 2010 年底,Michael Kay 一直在使用 GWT 将他的 Saxon XSLT 2.0 处理器编译为 Javascript(从而使其可用于所有 5 个主要浏览器)。很可能很快就会有一个轻量级的浏览器内撒克逊人。

于 2008-11-13T19:10:38.130 回答
4

您可以使用jQuery 的基本 XPath 插件来获得 XPath 查询功能。

此外,您可以考虑阅读有关 XPath XML 处理的这篇文章(同样使用 jQuery)

于 2008-10-08T15:33:46.660 回答
4

这就是我使用的

// xpath.js
// ------------------------------------------------------------------
//
// a cross-browser xpath class.
// Derived form code at http://jmvidal.cse.sc.edu/talks/javascriptxml/xpathexample.html.
//
// Tested in Chrome, IE9, and FF6.0.2
//
// Author     : Dino
// Created    : Sun Sep 18 18:39:58 2011
// Last-saved : <2011-September-19 15:07:20>
//
// ------------------------------------------------------------------

/*jshint browser:true */

(function(globalScope) {
    'use strict';

    /**
     * The first argument to this constructor is the text of the XPath expression.
     *
     * If the expression uses any XML namespaces, the second argument must
     * be a JavaScript object that maps namespace prefixes to the URLs that define
     * those namespaces.  The properties of this object are taken as prefixes, and
     * the values associated to those properties are the URLs.
     *
     * There's no way to specify a non-null default XML namespace. You need to use
     * prefixes in order to reference a non-null namespace in a query.
     *
     */

    var expr = function(xpathText, namespaces) {
        var prefix;
        this.xpathText = xpathText;    // Save the text of the expression
        this.namespaces = namespaces || null;  // And the namespace mapping

        if (document.createExpression) {
            this.xpathExpr = true;
            // I tried using a compiled xpath expression, it worked on Chrome,
            // but it did not work on FF6.0.2.  Threw various exceptions.
            // So I punt on "compiling" the xpath and just evaluate it.
            //
            // This flag serves only to store the result of the check.
            //

                // document.createExpression(xpathText,
                // // This function is passed a
                // // namespace prefix and returns the URL.
                // function(prefix) {
                //     return namespaces[prefix];
                // });
        }
        else {
            // assume IE and convert the namespaces object into the
            // textual form that IE requires.
            this.namespaceString = "";
            if (namespaces !== null) {
                for(prefix in namespaces) {
                    // Add a space if there is already something there
                    if (this.namespaceString.length>1) this.namespaceString += ' ';
                    // And add the namespace
                    this.namespaceString += 'xmlns:' + prefix + '="' +
                        namespaces[prefix] + '"';
                }
            }
        }
    };

    /**
     * This is the getNodes() method of XPath.Expression.  It evaluates the
     * XPath expression in the specified context.  The context argument should
     * be a Document or Element object.  The return value is an array
     * or array-like object containing the nodes that match the expression.
     */
    expr.prototype.getNodes = function(xmlDomCtx) {
        var self = this, a, i,
            doc = xmlDomCtx.ownerDocument;

        // If the context doesn't have ownerDocument, it is the Document
        if (doc === null) doc = xmlDomCtx;

        if (this.xpathExpr) {
            // could not get a compiled XPathExpression to work in FF6
            // var result = this.xpathExpr.evaluate(xmlDomCtx,
            //     // This is the result type we want
            //     XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
            //     null);

            var result = doc.evaluate(this.xpathText,
                xmlDomCtx,
                function(prefix) {
                    return self.namespaces[prefix];
                },
                XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
                null);

            // Copy the results into an array.
            a = [];
            for(i = 0; i < result.snapshotLength; i++) {
                a.push(result.snapshotItem(i));
            }
            return a;
        }
        else {
            // evaluate the expression using the IE API.
            try {
                // This is IE-specific magic to specify prefix-to-URL mapping
                doc.setProperty("SelectionLanguage", "XPath");
                doc.setProperty("SelectionNamespaces", this.namespaceString);

                // In IE, the context must be an Element not a Document,
                // so if context is a document, use documentElement instead
                if (xmlDomCtx === doc) xmlDomCtx = doc.documentElement;
                // Now use the IE method selectNodes() to evaluate the expression
                return xmlDomCtx.selectNodes(this.xpathText);
            }
            catch(e2) {
                throw "XPath is not supported by this browser.";
            }
        }
    };


    /**
     * This is the getNode() method of XPath.Expression.  It evaluates the
     * XPath expression in the specified context and returns a single matching
     * node (or null if no node matches).  If more than one node matches,
     * this method returns the first one in the document.
     * The implementation differs from getNodes() only in the return type.
     */
    expr.prototype.getNode = function(xmlDomCtx) {
        var self = this,
                doc = xmlDomCtx.ownerDocument;
        if (doc === null) doc = xmlDomCtx;
        if (this.xpathExpr) {

            // could not get compiled "XPathExpression" to work in FF4
            // var result =
            //     this.xpathExpr.evaluate(xmlDomCtx,
            //     // We just want the first match
            //     XPathResult.FIRST_ORDERED_NODE_TYPE,
            //     null);

            var result = doc.evaluate(this.xpathText,
                xmlDomCtx,
                function(prefix) {
                    return self.namespaces[prefix];
                },
                XPathResult.FIRST_ORDERED_NODE_TYPE,
                null);
            return result.singleNodeValue;
        }
        else {
            try {
                doc.setProperty("SelectionLanguage", "XPath");
                doc.setProperty("SelectionNamespaces", this.namespaceString);
                if (xmlDomCtx == doc) xmlDomCtx = doc.documentElement;
                return xmlDomCtx.selectSingleNode(this.xpathText);
            }
            catch(e) {
                throw "XPath is not supported by this browser.";
            }
        }
    };


    var getNodes = function(context, xpathExpr, namespaces) {
        return (new globalScope.XPath.Expression(xpathExpr, namespaces)).getNodes(context);
    };

    var getNode  = function(context, xpathExpr, namespaces) {
        return (new globalScope.XPath.Expression(xpathExpr, namespaces)).getNode(context);
    };


    /**
     * XPath is a global object, containing three members.  The
     * Expression member is a class modelling an Xpath expression.  Use
     * it like this:
     *
     *   var xpath1 = new XPath.Expression("/kml/Document/Folder");
     *   var nodeList = xpath1.getNodes(xmldoc);
     *
     *   var xpath2 = new XPath.Expression("/a:kml/a:Document",
     *                                   { a : 'http://www.opengis.net/kml/2.2' });
     *   var node = xpath2.getNode(xmldoc);
     *
     * The getNodes() and getNode() methods are just utility methods for
     * one-time use. Example:
     *
     *   var oneNode = XPath.getNode(xmldoc, '/root/favorites');
     *
     *   var nodeList = XPath.getNodes(xmldoc, '/x:derp/x:twap', { x: 'urn:0190djksj-xx'} );
     *
     */

    // place XPath into the global scope.
    globalScope.XPath = {
        Expression : expr,
        getNodes   : getNodes,
        getNode    : getNode
    };

}(this));
于 2011-09-19T19:08:59.313 回答
3

看看http://dev.abiss.gr/sarissa/项目。他们已将大部分与 XML 相关的 API 迁移到 IE,以及评估文档对象的方法。事实上,jQuery 没有 XPath 处理器,它有一个非常简单的路径选择器,例如:/a/b/c only

于 2008-10-08T15:52:00.573 回答
2

这是 Javascript 中 XPath 的最新跨浏览器实现: https ://github.com/andrejpavlovic/xpathjs

它功能齐全且经过单元测试,并具有强大的支持。最酷的部分是它还支持命名空间!

于 2012-01-31T13:56:43.907 回答
1

您可能想尝试支持跨浏览器工作的 XPath 2.0 语法的 jQuery XPath 插件。

于 2008-10-08T16:01:07.450 回答
0

我不认为它允许即席查询,但您可以查看 Johann Burkard 的XSLT jQuery 插件以获取有关如何实现 XPath 查询的灵感。我在我的jQuery Reference Dashboard 小部件中使用它,它非常可靠。

于 2008-10-09T08:33:36.197 回答
0

您可以利用每个浏览器现有的原生 DOM 支持。为此,您必须创建自己的包装器,原因是浏览器之间的差异。你可以看看http://dotnetcaffe.blogspot.com

最好的祝福

于 2009-12-15T08:45:54.773 回答
0

FormFaces(JS 中的 XForms 实现)具有可靠的 XPath 引擎,可以轻松提取和独立使用。

于 2010-03-22T12:21:29.187 回答
0

我认为您可以在这里使用 Cameron McCormack 的xpath 库。这对我来说非常有用。

于 2011-02-22T20:48:16.670 回答
0

另一个选项可能是LlamaLab XPath.js(虽然似乎有点旧)

于 2011-11-25T18:34:57.313 回答