Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Hi,

I'm trying to validate xml data using an xsd defined in memory (not a file).

I tried the following code :
C++
MSXML2::IXMLDOMParseErrorPtr pError;
MSXML2::IXMLDOMSchemaCollection2Ptr pSchemas;
HRESULT hr = pSchemas.CreateInstance(__uuidof(XMLSchemaCache60));

if(pSchemas)
{
  // Get Schema in memory (xsd is a buffer with the content of an xsd file)
  MSXML2::IXMLDOMDocumentPtr pSchema;
  hr = pSchema.CreateInstance(__uuidof(DOMDocument60));
  if(SUCCEEDED(hr))
  {
    pSchema->async = VARIANT_FALSE;
    hr = pSchema->loadXML(_bstr_t((const char*)xsd));
    if(hr==VARIANT_TRUE)
    {
      hr = pSchemas->add("",pSchema.GetInterfacePtr());
    }
    else
    {
	DisplayParseError(pSchema->parseError);
    }
  }
}
// Load the xml document and validate it
MSXML2::IXMLDOMDocument2Ptr xml;
HRESULT hRes = xml.CreateInstance(__uuidof(DOMDocument60));
if(SUCCEEDED(hRes))
{
  xml->validateOnParse = VARIANT_FALSE;
  xml->async = VARIANT_FALSE;

  if(pSchemas)
    xml->schemas = pSchemas.GetInterfacePtr();

  VARIANT_BOOL bRes = xml->loadXML(_bstr_t(xmlbuffer));
  if(VARIANT_TRUE==bRes)
  {
    pError = xml->validate();
    if(pError->errorCode == S_OK)
    {
      // XML is OK
    }
    else
    {
      DisplayValidateError(pError);
    }
  }
  else
  {
    DisplayParseError(xml->parseError);
  }
}


But I always got an E_FAIL error on
C++
pSchemas->add("",pSchema.GetInterfacePtr());


According to the documentation of IXMLDOMSchemaCollection, the second parameter of add is variant and can be a string to specify a file or a DOMDocument.

Can anyone tell me where I'm wrong ? What is missing ?

This code is adapted from a MSDN Example. But in this example, it's a XDR file loaded, not XSD...

I'm using MSXML6.
Posted

1 solution

Using the following code, I got extra information on the error
C++
try
{
	hr = pSchemas->add("",pSchema.GetInterfacePtr());
}
catch(_com_error &error)
{
	dump_com_error(error);
}


And the error was: (translated from french)
The namespace "" provided si different from the target namespace "http://tempuri.org/Device.xsd" of the schema.


When I generate the XSD file with Visual Studio 2010, it starts the file with:
XML
<xs:schema id="Device"
    targetNamespace="http://tempuri.org/Device.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/Device.xsd"
    xmlns:mstns="http://tempuri.org/Device.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>


The solution is to use the targetNamespace value as the first parameter of add method.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900