如何验证一个XML文件对于一个XSD文件(SCHEMA)的有效性?(举例说明)

如何验证一个XML文件对于一个XSD文件(SCHEMA)的有效性?(举例说明)
---------------------------------------------------------------

if you are using MSXML4, two methods (from MSXML4 documentation):
1. xml with xsi:schemaLocation:
var x = new ActiveXObject("MSXML2.DOMDocument.4.0");
x.async = false;
x.validateOnParse = true;
x.load("doc.xml");
if (x.parseError.errorCode != 0)
{
alert("errorReason=" + x.parseError.reason);
}
else
alert("===NO PARSE ERROR===\n" + x.xml);

2. otherwise, do something like

var xmldoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.4.0");
var SchemaCache = new ActiveXObject("Msxml2.XMLSchemaCache.4.0");
var SchemaCache2 = new ActiveXObject("Msxml2.XMLSchemaCache.4.0");

xmldoc.async = false;
xmldoc.validateOnParse = false;
SchemaCache.add("x-schema:books", "c:\\books.xsd");
SchemaCache2.addCollection(SchemaCache);
SchemaCache2.add("x-schema:books", "c:\\NewBooks.xsd");
xmldoc.schemas = SchemaCache2;
// The document will load only if a valid schema is attached to the xml
// file. The new schema will override the old one
xmldoc.load("c:\\books.xml");
alert(xmldoc.xml) ;

Published At
Categories with Web编程
comments powered by Disqus