2011-07-06 37 views

回答

3

XMLHttpRequet是否针对其XSD检查XML文档(如果存在)?

XMLHttpRequest只是一个方法名称,内容不必是XML(这就是为什么它通常与JSON,系列化的形式使用)。 XML解析器通常只会检查XML是否有效,而不是它是否符合特定的模式或DTD。我怀疑任何浏览器XML解析器都没有。

如果要检查模式或DTD,则需要XML验证程序,如XMLSpy中的验证程序。正如Harun发布的那样,您可能能够访问将进行验证的主机对象,但很可能不会跨浏览器。

2

JavaScript代码来验证对XSD的XML文件,

 <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文件,

 <?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文件(模式文件),

 <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> 

希望这有助于。 。

相关问题