Delphi XML 验证 XSD

Delphi XML validation with XSD

我正在使用 Delphi 10.2 更新 3。 我按照这些说明验证了生成的 xml 文档。

What effect does the attribute noNamespaceSchemaLocation have on XML parsing?

Validate XML using Windows DOM and TXMLDocument: doesn't work on some computers

schema validation with msxml in delphi

但是我有一个错误。 "The attribute 'noNamespaceSchemaLocation' on the element 'jegyzek_adatok' is not defined in the DTD/Schema."

正在准备 xml 文档:

const
  cSchemaLocation = 'noNamespaceSchemaLocation';

procedure PreparePostBookXMLDocument(ARootNode: IXMLNode);
var
  xDoc: IXMLDocument;
begin
  if ARootNode.OwnerDocument = nil then Exit;

  xDoc := ARootNode.OwnerDocument;
  xDoc.Version := '1.0';
  xDoc.Encoding := 'windows-1250';
  xDoc.Options := xDoc.Options + [doNodeAutoIndent];
  ARootNode.Attributes['xmlns:xsi'] := 'http://www.w3.org/2001/XMLSchema-instance';
  ARootNode.Attributes['xsi:' + cSchemaLocation] := 'https://www.posta.hu/static/internet/download/level_ver8_ugyfeleknek_8p4.xsd';
end;

验证:

function ValidatePostBookXMLDocument(ARootNode: IXMLNode): IResult;
var
  xDocument: IXMLDocument;
  xMsxmlDoc: IXMLDOMDocument3;
  xXSDDocument: IXMLDOMDocument3;
  xSchemaCache: IXMLDOMSchemaCollection;
  xSchemaLocation: string;
  xError: IXMLDOMParseError;
begin
  Result := ERRUnknown;
  try
    if ARootNode = nil then Exit;

    xDocument := ARootNode.OwnerDocument;
    if xDocument = nil then Exit;

    xMsxmlDoc := ((xDocument.DOMDocument as IXMLDOMNodeRef).GetXMLDOMNode as IXMLDOMDocument3);

    xSchemaLocation := ARootNode.AttributeNodes.FindNode(cSchemaLocation).Text;
    xXSDDocument := CoDOMDocument60.Create;
    xXSDDocument.async := False;
    xXSDDocument.validateOnParse := True;
    if not xXSDDocument.load(xSchemaLocation) then Exit(MakeErrorResult(ohFileError, 'A validációhoz szükséges séma fájlt nem sikerült betölteni!'));

    xSchemaCache := CoXMLSchemaCache60.Create;
    xSchemaCache.add('', xXSDDocument);
    xMsxmlDoc.schemas := xSchemaCache;
    xError := xMsxmlDoc.validate;
    case xError.errorCode of
      S_OK: Result := Success;
      else Exit(MakeErrorResult(ohError, xError.reason));
    end;
  except
    on E:Exception do Result := HandleException;
  end;
end;

生成的xml文件,通过https://www.freeformatter.com/xml-validator-xsd.html#有效。

The XSD (https://www.posta.hu/static/internet/download/level_ver8_ugyfeleknek_8p4.xsd):

My generated xml (on my google drive):

有人可以帮我吗?

我不知道您在 Delphi 中使用的特定 XML 解析器。但是,要回答一般问题:

  • 属性 xsi:noNamespaceSchemaLocation 声明在哪里可以找到文档的 XSD 模式(具体来说,是无命名空间中元素的模式)

  • 除非您调用 XSD 模式验证,否则它没有任何效果。一些解析器可能会将此属性的存在解释为调用模式验证的信号,但这是相当不寻常的。

  • 当针对 XSD 架构进行验证时,如果该属性的值是一个有效的 URI,则该属性始终有效。架构不需要明确允许此属性。

  • 当根据 DTD 进行验证时,此属性无效,除非 DTD 被写入明确允许它。

我怀疑您是 运行 启用了 DTD 验证的解析器,并且 DTD 不允许存在此属性。但这有点猜测。