使用XSD和XMLDOM进行XML验证 [英] XML validation using XSD and XMLDOM
问题描述
我正在尝试使用内存中定义的xsd(不是文件)来验证xml数据。
我尝试了以下代码:
Hi,
I'm trying to validate xml data using an xsd defined in memory (not a file).
I tried the following code :
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
pSchemas->add("",pSchema.GetInterfacePtr());
根据IXMLDOMSchemaCollection的文档,add的第二个参数是variant,可以是指定文件或DOMDocument的字符串。
谁能告诉我哪里错了?缺少什么?
此代码改编自MSDN示例。但是在这个例子中,它是一个加载的XDR文件,而不是XSD ...
我正在使用MSXML6。
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.
推荐答案
使用以下代码,我获得了有关错误的额外信息
Using the following code, I got extra information on the error
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.
当我使用Visual Studio 2010生成XSD文件时,它启动文件:
When I generate the XSD file with Visual Studio 2010, it starts the file with:
<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"
>
解决方案是使用 targetNamespace
值作为添加
方法。
这篇关于使用XSD和XMLDOM进行XML验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!