JavaScript處理XML DOM、XPath和XSLT方法詳解

一、瀏覽器對XML DOM的支持

1、將XML解析為DOM文檔

跨瀏覽器把XML解析為DOM文檔:

這個 parseXml()函數隻接收一個參數,即可解析的 XML 字符串。

function parseXml(xml) {
    var xmldom = null;

    if (typeof DOMParser != "undefined") {
        xmldom = (new DOMParser()).parseFromString(xml, "text/xml");
        var errors = xmldom.getElementsByTagName("parsererror");
        if (errors.length) {
            throw new Error("XML parsing error:" + errors[0].textContent);
        }
    } else if (typeof ActiveXObject != "undefined") {
        xmldom = createDocument();
        xmldom.loadXML(xml);
        if (xmldom.parseError != 0) {
            throw new Error("XML parsing error: " + xmldom.parseError.reason);
        }
    } else {
        throw new Error("No XML parser available.");
    }

    return xmldom;
}

2、將DOM文檔序列化為XML文檔

跨瀏覽器將DOM文檔序列化為XML文檔:

這個 serializeXml()函數接收一個參數,即要序列化的 XML DOM 文檔。

function serializeXml(xmldom) {

    if (typeof XMLSerializer != "undefined") {
        return (new XMLSerializer()).serializeToString(xmldom);
    } else if (typeof xmldom.xml != "undefined") {
        return xmldom.xml;
    } else {
        throw new Error("Could not serialize XML DOM.");
    }
}

二、瀏覽器對XPath的支持

跨瀏覽器使用XPath:重新創建 selectSingleNode()和selectNodes()方法。

命名空間對象應該是下面這種字面量的形式。

{
    prefix1: "uri1",
    prefix2: "uri2",
    prefix3: "uri3"
}

selectSingleNode和selectNodes函數接收三個參數:上下文節點、 XPath表達式和可選的命名空間對象。

selectSingleNode:

function selectSingleNode(context, expression, namespaces) {
    var doc = (context.nodeType != 9 ? context.ownerDocument: context);

    if (typeof doc.evaluate != "undefined") {
        var nsresolver = null;
        if (namespaces instanceof Object) {
            nsresolver = function(prefix) {
                return namespaces[prefix];
            };
        }

        var result = doc.evaluate(expression, context, nsresolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
        return (result !== null ? result.singleNodeValue: null);

    } else if (typeof context.selectSingleNode != "undefined") {
        //create namespace string
        if (namespaces instanceof Object) {
            var ns = "";
            for (var prefix in namespaces) {
                if (namespaces.hasOwnProperty(prefix)) {
                    ns += "xmlns:" + prefix + "='" + namespaces[prefix] + "' ";
                }
            }
            doc.setProperty("SelectionNamespaces", ns);
        }
        return context.selectSingleNode(expression);
    } else {
        throw new Error("No XPath engine found.");
    }
}
//調用
var result = selectSingleNode(xmldom.documentElement, "wrox:book/wrox:author", { wrox: <a href="http://www.wrox.com/" rel="external nofollow"  rel="external nofollow"   target="_blank">http://www.wrox.com/</a>});
alert(serializeXml(result));

selectNodes:

function selectNodes(context, expression, namespaces) {
    var doc = (context.nodeType != 9 ? context.ownerDocument: context);

    if (typeof doc.evaluate != "undefined") {
        var nsresolver = null;
        if (namespaces instanceof Object) {
            nsresolver = function(prefix) {
                return namespaces[prefix];
            };
        }

        var result = doc.evaluate(expression, context, nsresolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
        var nodes = new Array();

        if (result !== null) {
            for (var i = 0,
            len = result.snapshotLength; i < len; i++) {
                nodes.push(result.snapshotItem(i));
            }
        }

        return nodes;
    } else if (typeof context.selectNodes != "undefined") {

        //create namespace string
        if (namespaces instanceof Object) {
            var ns = "";
            for (var prefix in namespaces) {
                if (namespaces.hasOwnProperty(prefix)) {
                    ns += "xmlns:" + prefix + "='" + namespaces[prefix] + "' ";
                }
            }
            doc.setProperty("SelectionNamespaces", ns);
        }
        var result = context.selectNodes(expression);
        var nodes = new Array();

        for (var i = 0,
        len = result.length; i < len; i++) {
            nodes.push(result[i]);
        }

        return nodes;
    } else {
        throw new Error("No XPath engine found.");
    }
}
//調用
var result = selectNodes(xmldom.documentElement, "wrox:book/wrox:author", {wrox: <a href="http://www.wrox.com/" rel="external nofollow"  rel="external nofollow"   target="_blank">http://www.wrox.com/</a>});
alert(result.length);

三、瀏覽器對使用XSLT的支持

跨瀏覽器使用XSLT樣式表轉換XML文檔

這個 transform()函數接收兩個參數:要執行轉換的上下文節點和 XSLT 文檔對象。

function transform(context, xslt) {
    if (typeof XSLTProcessor != "undefined") {
        var processor = new XSLTProcessor();
        processor.importStylesheet(xslt);

        var result = processor.transformToDocument(context);
        return (new XMLSerializer()).serializeToString(result);

    } else if (typeof context.transformNode != "undefined") {
        return context.transformNode(xslt);
    } else {
        throw new Error("No XSLT processor available.");
    }
}

到此這篇關於JavaScript處理XML DOM、XPath和XSLT的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: