#include <stdio.h> #import <msxml5.dll> using namespace MSXML2; int main(int argc, char* argv[]) { HRESULT hr; CoInitialize(NULL); IXMLDOMDocument3Ptr pXMLDoc; hr = pXMLDoc.CreateInstance(__uuidof(DOMDocument50)); if (FAILED(hr)) { printf("Failed to CreateInstance on an XML DOM"); return -1; } pXMLDoc->async = VARIANT_FALSE; pXMLDoc->validateOnParse = VARIANT_FALSE; hr = pXMLDoc->setProperty("MultipleErrorMessages", VARIANT_TRUE); if (FAILED(hr)) { printf("Failed to enable mulitple validation errors\n"); return -1; } if(pXMLDoc->load("books.xml")!=VARIANT_TRUE) { printf("Failed to load DOM from books.xml. %s\n", (LPCSTR)pXMLDoc->parseError->reason); return -1; } IXMLDOMDocument3Ptr pXSDDoc; hr = pXSDDoc.CreateInstance(__uuidof(DOMDocument50)); if (FAILED(hr)) { printf("Failed to CreateInstance on an XSD Doc"); return -1; } pXSDDoc->async = VARIANT_FALSE; pXSDDoc->validateOnParse = VARIANT_FALSE; if(pXSDDoc->load("books.xsd")!=VARIANT_TRUE) { printf("Failed to load XSD from books.xsd. %s\n", (LPCSTR)pXSDDoc->parseError->reason); return -1; } IXMLDOMSchemaCollectionPtr pSCache; hr = pSCache.CreateInstance(__uuidof(XMLSchemaCache50)); if (FAILED(hr)) { printf("Cannot instantiate XMLSchemaCache50\n"); return -1; } pXMLDoc->schemas = pSCache.GetInterfacePtr(); hr = pSCache->add("urn:books", pXSDDoc.GetInterfacePtr()); if (FAILED(hr)) { printf("Cannot add 'urn:books' to schema cache.\n"); return -1; } // Validate the entire DOM. printf("Validating DOM...\n"); IXMLDOMParseError2Ptr pError =pXMLDoc->validate(); if (pError->errorCode != 0) { printf("invalid dom:\n%s",(LPCSTR)pError->reason); printf("errorXPath:\n%s\n",(LPCSTR)pError->errorXPath); } else printf("DOM is valid:\n%s\n",(LPCSTR)pXMLDoc->xml); // Validate DOM fragments. printf("\n\nvalidating nodes...\n"); IXMLDOMNodeListPtr pNList; pNList = pXMLDoc->selectNodes("//book"); IXMLDOMNodePtr pNode; for (int i=0; i<pNList->length; i++) { pNode = pNList->item[i]; pError = pXMLDoc->validateNode(pNode); if (pError->errorCode !=0) { printf("\nNode is invalid:\n%s", (LPCSTR)pError->reason); printf("errorXPath:\n%s\n", (LPCSTR)pError->errorXPath); } else { printf("\nNode is valid:\n%s\n", (LPCSTR)pNode->xml); } } pError.Release(); pXMLDoc.Release(); pXSDDoc.Release(); pSCache.Release(); pNList.Release(); pNode.Release(); CoUninitialize(); return 0; }
Try It!
Note You can also copy these files into the project's main directory using Windows Explorer (or a command prompt).