如何使用javascript验证xml文件?
我的函数将加载一个本地xml文件,并检查它是否格式正确。如果格式不正确,则弹出警报。 这是我加载xml文件的函数:如何使用javascript验证xml文件?,javascript,xml,Javascript,Xml,我的函数将加载一个本地xml文件,并检查它是否格式正确。如果格式不正确,则弹出警报。 这是我加载xml文件的函数: if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",xml_url,false);
xmlhttp.send(null);
xmlDoc=xmlhttp.responseXML;
我的程序在Firefox中运行。
是否有任何简单的方法来验证xml文件?
谢谢大家! 您需要通过FireFox的API调用FireFox的XML解析器(我自己没有用过)。看起来这可能有用: 但这里有一个更老的解决方案,看起来像是使用IE的MSXML(这是他们的XML解析器):
要验证什么?如果xml文件格式不正确,例如。。。。。。。我想检测此类错误,然后弹出一个警报。此旧解决方案是否兼容跨浏览器?它在Firefox和Chrome中工作吗?如果没有,你能给我一些有用的链接来找到解决方案吗?我只是在寻找一个好的解决方案,它可以在客户端验证XML文件。:)
//We'll load the XML data into an MSXML DOM Document
//We'll load in the XSD
//We'll validate the data and report on the results
var xmlData = new ActiveXObject("MSXML2.DOMDocument.5.0")
xmlData.async = false
//A SchemaCache is an object that can hold one or more schema references
var xsd = new ActiveXObject("MSXML2.XMLSchemaCache.5.0")
//Each schema you wish to reference must be added to the cache
//The first argument is for the Namespace URI
xsd.add("", "order.xsd")
//Tell the XMLDOMDocument where the schema(s) can be found
xmlData.schemas = xsd
//You don't want to load your "instance document"
//until you've indicated that a schema should be used
xmlData.validateOnParse = true //This is the default anyway
xmlData.load("Order1.xml")
if(xmlData.parseError.reason != "")
{
//There is either a "well-formed" or "validation" problem
alert(xmlData.parseError.reason)
}
else
{
alert("Document is well-formed and valid!")
}