Does XMLHttpRequest check XML documents against their XSD if it exists?
If not, is there any way to che开发者_如何转开发ck the XML document against it's XSD?
Does XMLHttpRequet check XML documents against their XSD if it exists?
No.
XMLHttpRequest is just a method name, the content doesn't have to be XML (which is why it is commonly used with JSON and serialised forms). An XML parser will usually only check that the XML is valid, not whether it conforms to a particular schema or DTD. I doubt that any browser XML parser does.
If you want to check against a schema or DTD, you need an XML validator such as the one in XMLSpy. As Harun has posted, you might be able to access a host object that will do validation but it most likely will not be cross-browser.
JavaScript code to validate the xml file against the xsd,
<SCRIPT LANGUAGE="JavaScript">
var strFile=path of xml file;
function validateFile(strFile)
{
// Create a schema cache and add books.xsd to it.
var xs = new ActiveXObject("MSXML2.XMLSchemaCache.4.0");
xs.add("urn:books", "xsd path");
// Create an XML DOMDocument object.
var xd = new ActiveXObject("MSXML2.DOMDocument.4.0");
// Assign the schema cache to the DOMDocument's
// schemas collection.
xd.schemas = xs;
// Load books.xml as the DOM document.
xd.async = false;
xd.validateOnParse = true;
xd.resolveExternals = true;
xd.load(strFile);
// Return validation results in message to the user.
if (xd.parseError.errorCode != 0)
{
return("Validation failed on " + strFile +
"\n=====================" +
"\nReason: " + xd.parseError.reason +
"\nSource: " + xd.parseError.srcText +
"\nLine: " + xd.parseError.line + "\n");
}
else
return("Validation succeeded for " + strFile +
"\n======================\n" +
xd.xml + "\n");
}
</SCRIPT>
XML file,
<?xml version="1.0"?>
<bookstore xmlns="generic">
<book genre="autobiography">
<title>The Autobiography of Benjamin Franklin</title>
<price>89.88</price>
</book>
<book genre="novel">
<title>The Confidence Man</title>
<price>11.99</price>
</book>
</bookstore>
XSD file(schema file),
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="generic" elementFormDefault="qualified" targetNamespace="generic">
<xsd:element name="bookstore" type="bookstoreType"/>
<xsd:complexType name="bookstoreType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="book" type="bookType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bookType">
<xsd:sequence>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="price" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="genre" type="xsd:string"/>
</xsd:complexType>
</xsd:schema>
Hope this helps..
精彩评论