Einzelnen Beitrag anzeigen

Fritzew

Registriert seit: 18. Nov 2015
Ort: Kehl
627 Beiträge
 
Delphi 10.2 Tokyo Enterprise
 
#2

AW: Validieren einer XML die 99.te

  Alt 2. Nov 2018, 10:23
Wir benutzen hier:

Delphi-Quellcode:
unit XMLValidate;


// Requirements ----------------------------------------------------------------
//
// MSXML 4.0 Service Pack 1
// http://www.microsoft.com/downloads/release.asp?releaseid=37176
//
// -----------------------------------------------------------------------------

interface

uses
  SysUtils;

type
  EValidateXMLError = class(Exception)
  private
    FErrorCode: Integer;
    FerrorLine: Integer;
    FReason: string;

  public
    constructor Create(AErrorCode: Integer; const Aline: Integer; const AReason: string);
    property ErrorCode: Integer read FErrorCode;
    property Reason: string read FReason;
  end;

procedure ValidateXMLDoc(const XmlTestFile, SchemaLocation, SchemaNS: WideString); overload;

implementation

uses
  Windows,
  ComObj,
  MSXML2_TLB;

resourcestring
  RsValidateError = 'Validate XML Error (%.8x), Line (%D), Reason: %s';

  { EValidateXMLError }

constructor EValidateXMLError.Create(AErrorCode: Integer; const Aline: Integer; const AReason: string);
begin
  inherited CreateResFmt(@RsValidateError, [AErrorCode, Aline, AReason]);
  FErrorCode := AErrorCode;
  FReason := AReason;
  FerrorLine := Aline;
end;

procedure ValidateXMLDoc(const XmlTestFile, SchemaLocation, SchemaNS: WideString);
var
  xml, xsd: IXMLDOMDocument2;
  cache: IXMLDOMSchemaCollection;
  res: boolean;
  err: IXMLDOMParseError;
begin
  xsd := CoDOMDocument40.Create;
  xsd.async := False;
  xsd.load(SchemaLocation);

  cache := CoXMLSchemaCache40.Create;
  cache.add(SchemaNS, xsd);

  xml := CoDOMDocument40.Create;
  xml.async := False;
  xml.schemas := cache;
  err := nil;
  res := xml.load(XmlTestFile);
  if not res then
    begin
      err := xml.parseError;
      if err <> nil then
        raise EValidateXMLError.Create(err.ErrorCode, err.line, err.Reason);
    end;
end;

end.
Aufruf:

Delphi-Quellcode:
function Txmlmod.internValidatefile(aXmlFileName: string; errorlst: Tstrings): boolean;
var
   lSchemaFilename: string;
begin
   result := false;
   lSchemaFilename := Tpath.combine(Tpath.GetDirectoryName(Globals.XMLData), 'schema_400.xsd');
   try
      ValidateXMLDoc(aXmlFileName, lSchemaFilename, 'http://www.xmlData.com/xmlInvoice/XSD');
      result := true;
   except
      on e: EValidateXMLError do
         begin
            errorlst.add(e.Message);
         end
   end;
end;
Fritz Westermann
  Mit Zitat antworten Zitat