这里有点麻烦。我正在尝试解析这个XSL文件:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="utf-8" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Events</title>
</head>
<body>
<dl>
<xsl:for-each select="all/event">
<xsl:sort select="substring(@displayuntil,7,4)" data-type="number" /> <!-- year -->
<xsl:sort select="substring(@displayuntil,1,2)" data-type="number" /> <!-- month -->
<xsl:sort select="substring(@displayuntil,4,2)" data-type="number" /> <!-- day -->
<dt>
<xsl:value-of select="@displayuntil" />
--
<xsl:value-of select="@title" />
</dt>
<dd>
<xsl:value-of select="description" disable-output-escaping="yes" />
</dd>
</xsl:for-each>
</dl>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
使用以下JavaScript代码,取自w3schools:
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
} else {
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
alert(xhttp.responseText); // displays the contents of the document
alert(xhttp.responseXML.xml); // in IE, displays nothing
return xhttp.responseXML;
}
xhttp.responseText
警告显示我的文档,因此我知道它正在加载。 xhttp.responseXML.xml
警报为空,因此显然它不是格式良好的XML文件。
我通过http://XMLvalidation.com运行它并且没有错误。那么我忽略了什么?
答案 0 :(得分:1)
它对我有用。
我只是将javascript代码附加到按钮单击,然后将xsl放入服务器上的文件中。当我点击按钮时,我收到两个警报,两个内容基本相同。
可能是您遇到过时的缓存。我昨天碰到了这个。我正在使用XHR来检索XML文件,而我正在获取旧版本。如果您一直在更改xsl,则可能是网页检索的文档是旧版本,也可能无效。为避免这种情况,请将?_<random number>
附加到网址。
此外,您应该在函数中最多声明一次var。在Javascript中,vars具有函数作用域,因此无论在何处放置var
声明,该变量名称在整个函数中都是已知的。这意味着将所有变量放在函数顶部是一种很好的编码风格,无论您在何处使用它们。实际上,在if子句和else子句中声明具有相同名称的var是一种冲突;我不知道JS引擎会对此做些什么,但严格来说这并不合理。虽然容易改变。
编辑 - 最后,您应该使用更新的ProgId。有关说明,请参阅this blog post from Microsoft。实际上你不需要解释,短篇小说是Microsoft.XMLHTTP
是错误的。你应该使用的是MSXML2.XMLHTTP
。
通过这些更改,我的代码如下所示:
function loadXMLDoc(dname) {
var xhr = null,
d = new Date(),
noCacheUrl = dname + "?_=" + d.valueOf();
// if the original document is mblase.xsl, then the "no cache" url will be
// sth like mblase.xsl?_399383932 , where the number varies for each request.
// The 'query string' will be discarded and you will get the same static file.
// This insures that you always get a fresh copy of the xsl document.
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("MSXML2.XMLHTTP"); // current, correct ProgId
}
xhr.open("GET",noCacheUrl,false);
xhr.send();
alert(xhr.responseText); // displays the contents of the document
alert(xhr.responseXML.xml); // displays an indented version of the XSL document
return xhr.responseXML;
}
如果无缓存技巧不起作用,那么您需要进一步诊断。如果我试图诊断这个,我会简化XSL文件 - 使它只是一个XML文件,非常简单,看看你是否可以让它工作。然后逐渐加回复杂性。这将允许您避免或排除无效/格式错误的XML问题。