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

标签 xml delphi xsd dtd 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。”

我该怎么办?

最佳答案

我想出了一个似乎有效的方法。我首先显式加载架构,然后将它们添加到架构集合中。接下来我加载 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 进行验证。

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

关于xml - 在 delphi 中使用 msxml 进行模式验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/446635/

相关文章:

.net - 从 XSD 生成类

c# - 为什么 XmlDocument Validate 事件处理程序没有被命中?

xml - 您可以转换无序的 xml 以匹配 xsd :sequence order?

java - 无法找到或加载主类com.liferay.portal.tools.SassToCssBuilder

xml - 在 bash 中使用 Regex 删除 XML 注释

xml - Win7/64位 : Notepad++ XML Tools Plugin does not load

delphi - 有没有一种可以在Windows 98中使用RAD Studio XE7编译程序的方法?

SQL Server : Find records where XML is missing tag

delphi - BCB/德尔福 : I am doing something stupid - but what?

delphi - T编辑焦点和插入符