在 delphi 中使用 msxml 进行架构验证 [英] schema validation with msxml in delphi

查看:13
本文介绍了在 delphi 中使用 msxml 进行架构验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据它引用的模式验证 XML 文件.(使用 Delphi 和 MSXML2_TLB.)(相关部分)代码如下所示:

I'm trying to validate an XML file against the schemas it references. (Using Delphi and MSXML2_TLB.) The (relevant part of the) code looks something like this:

procedure TfrmMain.ValidateXMLFile;
var
    xml: IXMLDOMDocument2;
    err: IXMLDOMParseError;
    schemas: IXMLDOMSchemaCollection;
begin
    xml := ComsDOMDocument.Create;
    if xml.load('Data/file.xml') then
    begin
        schemas := xml.namespaces;
        if schemas.length > 0 then
        begin
            xml.schemas := schemas;
            err := xml.validate;
        end;
    end;
end;

这会导致缓存被加载(schemas.length > 0),但是接下来的赋值引发了一个异常:only XMLSchemaCache-schemacollections can be used."

This has the result that cache is loaded (schemas.length > 0), but then the next assignment raises an exception: "only XMLSchemaCache-schemacollections can be used."

我该怎么办?

推荐答案

我想出了一个似乎可行的方法.我首先显式加载模式,然后将它们添加到模式集合中.接下来我加载 xml 文件并将 schemacollection 分配给它的 schemas 属性.现在的解决方案如下所示:

I've come up with an approach that seems to work. I first load the schema's explicitly, then add themn to the schemacollection. Next I load the xml-file and assign the schemacollection to its schemas property. The solution now looks like this:

uses MSXML2_TLB  
That is:  
// Type Lib: C:Windowssystem32msxml4.dll  
// LIBID: {F5078F18-C551-11D3-89B9-0000F81FE221}

function TfrmMain.ValidXML(
    const xmlFile: String; 
    out err: IXMLDOMParseError): Boolean;
var
    xml, xsd: IXMLDOMDocument2;
    cache: IXMLDOMSchemaCollection;
begin
    xsd := CoDOMDocument40.Create;
    xsd.Async := False;
    xsd.load('http://the.uri.com/schemalocation/schema.xsd');

    cache := CoXMLSchemaCache40.Create;
    cache.add('http://the.uri.com/schemalocation', xsd);

    xml := CoDOMDocument40.Create;
    xml.async := False;
    xml.schemas := cache;

    Result := xml.load(xmlFile);
    if not Result then
      err := xml.parseError
    else
      err := nil;
end;

使用 XMLSchemaCache40 或更高版本很重要.早期版本不遵循 W3C XML Schema 标准,而仅根据 MicroSoft 规范 XDR Schema 进行验证.

It is important to use XMLSchemaCache40 or later. Earlier versions don't follow the W3C XML Schema standard, but only validate against XDR Schema, a MicroSoft specification.

此解决方案的缺点是我需要显式加载架构.在我看来,应该可以自动检索它们.

The disadvantage of this solution is that I need to load the schema's explicitly. It seems to me that it should be possible to retrieve them automatically.

这篇关于在 delphi 中使用 msxml 进行架构验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆