一、浏览器对XML DOM的支持
1.判断浏览器对DOM2.0级别的XML的支持
alert(document.implementation.hasFeature("XML", "2.0")); // true
2.解析XML
// 在ie8以下创建XML
function createXML() {
if(typeof arguments.callee.activeXString != "string"){
var versions = ["MSXML2.DOMDocument", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument.6.0"], i, len;
for (i = 0, len = versions.length; i < len ; i++)
{
try
{
new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
break;
}
catch (error){}
}
}
return new ActiveXObject(arguments.callee.activeXString);
}
// 解析XML字符串为XML DOM对象
function parseXml (xml) {
var xmlDom;
if (typeof DOMParser != "undefined")
{
xmlDom = (new DOMParser()).parseFromString(xml, "text/xml");
var errors = xmlDom.getElementsByTagName("parsererror");
if(errors.length)
{
throw new Error(errors[0].textContent);
}
//alert(xmlDom.documentElement.tagName);
} else if (typeof ActiveXObject != "undefined")
{
xmlDom = new createXML();
xmlDom.loadXML(xml);
if (xmlDom.parseError != 0)
{
throw new Error(xmlDom.parseError.reason);
}
//alert(xmlDom.xml);
} else {
throw new Error("不支持xml dom");
}
return xmlDom;
}
// 测试
var xmldom = null;
try {
xmldom = parseXml("<root><child/></root>");
} catch (ex){
alert(ex.message);
}
alert(xmldom);
3.序列化xml
function serializeXml(xmldom){
if (typeof XMLSerializer != "undefined"){
return (new XMLSerializer()).serializeToString(xmldom);
} else if (typeof xmldom.xml != "undefined"){
// Less IE8
return xmldom.xml;
} else {
throw new Error("Could not serialize XML DOM.");
}
}
// 测试
var xmldom = null;
try {
xmldom = parseXml("<root><child/></root>");
} catch (ex){
alert(ex.message);
}
var serizlize = serializeXml(xmldom);
alert(serizlize); // <root><child/></root>
4.加载xml文件
function parseXmlFile(file) {
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e) {alert(e.message)}
}
try
{
xmlDoc.async=false;
xmlDoc.load(file);
}
catch(e) {alert(e.message)}
return xmlDoc;
}
二、浏览器对XPATH的支持
1.判断浏览器对DOM3的XPath的支持
alert(document.implementation.hasFeature("XPath", "3.0")); // true
2.跨浏览器兼容
/**根据
* param context : XML DOM上下文环境
* param expression : XPath的查询表达式
* param namespaces : 命名空间
*/
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"){
// 创建命名空间字符串
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 xmldom = null;
try {
xmldom = parseXml("<yc:root xmlns:yc=\"http://www.yc.com/\"><yc:child>zhangshan</yc:child><yc:child>lisi</yc:child></yc:root>");
} catch (ex){
alert(ex.message);
}
var result = selectNodes(xmldom.documentElement, "yc:child",
{ yc: "http://www.yc.com/"});
for(var i = 0, len = result.length; i < len; i++) {
alert(result[i].firstChild.nodeValue); // zhangshan,lisi
}
三、浏览器对XLST的支持 将xml文件用xsl文件修饰,形成为html文件,html文件包括xml的内容和xsl的样式
下面我们来讲一个例子,大体是用javascript操作xml文件和xsl文件,将他们合并为html形式的文件当然,
我们返回的是html形式的字符串,以下是具体步骤:
1.准备文件cdcatalog.xml和cdcatalog.xsl
①cdcatalog.xml文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited with XML Spy v2007 (http://www.altova.com) -->
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
</catalog>
②cdcatalog.xsl文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited with XML Spy v2007 (http://www.altova.com) -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method='html' version='1.0' encoding='UTF-8' indent='yes'/>
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th align="left">Title</th>
<th align="left">Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
2.用javascript将两个文件加载,用上述的parseXmlFile函数
var xmldom = parseXmlFile("xml/cdcatalog.xml");
var xsltdom = parseXmlFile("xml/cdcatalog.xsl");
3.将xml文件和xsl文件转换为字符串
function transform(context, xslt){
if (typeof XSLTProcessor != "undefined"){
// 创建XSLTProcessor对象
var processor = new XSLTProcessor();
// 导入xslt样式表
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.");
}
}
var result = transform(xmldom, xsltdom);
alert(result); // html形式的字符串
4.接下来就是将result返回的字符串拷贝下来,放入一个html文件中就可以看到效果了。
网友评论