乐趣区

JS学习笔记第18章JavaScript与XML

本章主要讲解了以下四个问题:

1、将 XML 解析为 DOM 文档

跨浏览器把 XML 解析为 DOM 文档:

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;
        }
  

这个 parseXml() 函数只接收一个参数,即可解析的 XML 字符串。

2、将 DOM 文档序列化为 XML 文档

跨浏览器将 DOM 文档序列化为 XML 文档:

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.");
            }
        }

这个 serializeXml() 函数接收一个参数,即要序列化的 XML DOM 文档。

3、XPath

跨浏览器使用 XPath:
重新创建 selectSingleNode() 和 selectNodes() 方法。函数接收三个参数:上下文节点、XPath 表达式和可选的命名空间对象。命名空间对象应该是下面这种字面量的形式。

{
    prefix1: "uri1",
    prefix2: "uri2",
    prefix3: "uri3"
}
 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: "http://www.wrox.com/"});            
alert(serializeXml(result));
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: "http://www.wrox.com/"});            
alert(result.length); 

4、使用 XSLT 样式表转换 XML 文档

跨浏览器使用 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.");
                }
            }

这个 transform() 函数接收两个参数:要执行转换的上下文节点和 XSLT 文档对象。

退出移动版