perfectxml.com
 Basic Search  Advanced Search   
Topics Resources Free Library Software XML News About Us
home » focus » msxml » ask a question » past questions & answers Friday, 12 October 2007
 
NEWS
MSXML 4.0 SP2 now available!

 
MSXML
Basics
DOM
SAX
XPath
XSLT
Schemas
SOM
HTTP Access
.NET
Data Islands
Ask a Question
   Past Q&As
C++ Samples
DLL/Version Info
Reference Guide
Books
KB Articles
   HOW TO
   SAMPLE
   INFO
   BUG/PRB
   FIX
   Misc.
MSXML Tips
   August 2002
   September 2002
MSXML Tools

Microsoft XML Core Services


Go back to list of previously asked questions and answers

Question: I am using MSXML 4.0 in an ASP page to create an XMLDOMDocument based on the posted form data. I need to validate the created XML document against an .xsd schema file on the server.
Asked By: David
Viewed: 1492
Answer: You may use the XMLSchemaCache object and DOMDocument Validate method to validated the loaded XML document against the schema. Here is the drill:

Here is the .xsd schema file on the server, the file is called FormData.xsd
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="FormData" type="FormDataType"/>
  <xs:complexType name="FormDataType">
    <xs:sequence>
      <xs:element name="PostedData1" type="xs:string"/>
      <xs:element name="PostedData2" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>
The above schema requires XML document to have FormData root element and two child nodes name PostedData1 and PostedData2 of type string. Let' look at the ASP code (BuildAndValidate.asp) now:

First build (create) the XML document based on the posted form data:
<%
Option Explicit
Dim objXMLDom
Dim objSchCache
Dim anElem
Dim ValidationResult
	
Set objXMLDom = Server.CreateObject("Msxml2.DOMDocument.4.0")
Set objSchCache = Server.CreateObject("Msxml2.XMLSchemaCache.4.0")
	
objXMLDom.loadXML "<FormData/>"
	
Set anElem = objXMLDom.createElement ("PostedData1")
anElem.nodeTypedValue = "FormFieldVal1"
objXMLDom.documentElement.appendChild anElem

'Comment following three lines to see the validation error
Set anElem = objXMLDom.createElement ("PostedData2")
anElem.nodeTypedValue = "FormFieldVal2"
objXMLDom.documentElement.appendChild anElem
Let's now validate the created XML Document:

'Document is created, let's now validate it
objSchCache.Add "", Server.MapPath("FormData.xsd")
Set objXMLDom.schemas = objSchCache

Set ValidationResult = objXMLDom.Validate()
If ValidationResult.errorCode = 0 Then
    Response.Write "Validation OK<br><br>" & Server.HTMLEncode(objXMLDom.xml)
Else
    Response.Write "Validation Error: " & ValidationResult.reason
End If
	
Set objSchCache = nothing	
Set objXMLDom = nothing
%>


Go back to list of previously asked questions and answers
  Contact Us | E-mail Us | Site Guide | About PerfectXML | Advertise ©2004 perfectxml.com. All rights reserved. | Privacy