如何使用javascript验证xml文件?

时间:2016-01-31 18:25:25

标签: javascript xml

我的功能是加载本地xml文件并检查是否格式正确。如果格式不正确,则弹出警报。 这是我加载xml文件的函数:

        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文件? 谢谢!

1 个答案:

答案 0 :(得分:0)

您需要通过其API(我自己没有使用过)调用FireFox的XML解析器。看起来这可能有效:https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Error_handling

但这是一个较老的解决方案,看起来像使用IE的MSXML(这是他们的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!")
 }