微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在delphi中使用msxml进行模式验证

我正在尝试根据它引用的模式验证XML文件. (使用Delphi和MSXML2_TLB.)代码的(相关部分)看起来像这样:
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),但是下一个赋值会引发异常:“只能使用XMLSchemaCache-schemacollections.”

我该怎么办呢?

解决方法

我想出了一种似乎有用的方法.我首先显式加载模式,然后将它们添加到schemacollection.接下来,我加载xml文件并将schemacollection分配给其schemas属性.解决方案现在看起来像这样:
uses MSXML2_TLB  
That is:  
// Type Lib: C:\Windows\system32\msxml4.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进行验证.

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

原文地址:https://www.jb51.cc/delphi/103066.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐