Я ищу библиотеку XPath для запроса документов XML в FF, IE, Opera и Safari... и не смог найти ее. Вы видели что-то?
Кросс-браузерная реализация XPath в JavaScript
Ответ 1
Google только что выпустил Wicked Good XPath - переписывает известный Cybozu Lab JavaScript-XPath.
Ссылка: https://github.com/google/wicked-good-xpath
Переписанная версия на 40% меньше и примерно на 30% быстрее, чем исходная реализация.
Ответ 2
Google AJAXSLT проект с открытым исходным кодом хорошо соответствует заявленным требованиям.
Как говорится в их собственном описании:
"AJAXSLT - это реализация XSLT в JavaScript. Поскольку XSLT использует XPath, , это также реализация XPath, которая может использоваться независимо от XSLT. что он делает XSLT равномерно доступным для большего количества браузеров, чем изначально предоставляет его, и что при необходимости он может быть расширен до еще большего количества браузеров. AJAXSLT интересен для разработчиков, которые стремятся агрессивно кросс совместимость браузера своих передовых веб-приложений. "
ОБНОВЛЕНИЕ. В конце 2010 года Майкл Кей собирал свой процессор Saxon XSLT 2.0 для Javascript (таким образом, он был доступен для всех 5 основных браузеров) с использованием GWT. Скорее всего, скоро появится скоростной браузер Saxon.
Ответ 3
Вы можете использовать базовый плагин XPath для jQuery, чтобы получить функциональные возможности запроса XPath.
Кроме того, вы можете рассмотреть эту статью о XML-обработке XPath (снова с jQuery)
Ответ 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 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));
Ответ 5
Взгляните на http://dev.abiss.gr/sarissa/. Они перенесли большую часть связанных с XML API-интерфейсов в IE, а также оценили метод объекта документа. И действительно, у jQuery нет процессора XPath, у него очень простой селектор пути, например:/a/b/c only
Ответ 6
Вот самая новая кроссбраузерная реализация XPath в Javascript: https://github.com/andrejpavlovic/xpathjs
Он полностью функциональный и модульный, и имеет большую поддержку. Самая крутая часть состоит в том, что он также поддерживает пространства имен!
Ответ 7
Возможно, вы захотите попробовать jQuery XPath plugin с поддержкой XPath 2.0, который работает кросс-браузер.
Ответ 8
Я не думаю, что он разрешает специальные запросы, но вы можете взглянуть на Johann Burkard плагин XSLT jQuery за вдохновение в том, как реализовать запросы XPath. Я использую его в своем jQuery Reference Виджет панели инструментов и он действительно прочен.
Ответ 9
Вы можете использовать существующую поддержку встроенного DOM для каждого браузера. Для этого вам придется создать свою собственную оболочку, причина в различии между браузером. Вы можете взглянуть на http://dotnetcaffe.blogspot.com
С наилучшими пожеланиями
Ответ 10
FormFaces (реализация XForms в JS) имеет надежный механизм XPath, который можно легко извлечь и использовать независимо.
Ответ 11
Я думаю, вы можете использовать Cameron McCormack xpath library здесь. Это отлично работает для меня.
Ответ 12
Другой вариант может быть LlamaLab XPath.js (хотя кажется немного старым)