How to validate a IXMLDocument against a XML Schema?

Hello Delphi gurus

I have a project where a handle a XML document, mapped to ObjectPascal with the help of XML Data Bind wizard. I have a schema (XSD) file that describes the XML document and it worked fine to generate the Delphi unit I use to handle the XML nodes in a high level fashion.

However, I need to validate XML documents saved as files against the very same XSD file I used in XML Data Bind wizard. So, I created a .rc file so I won´t need a XSD file to be released with my project.

After deep digging throught the XML units source file, I count´t find any interface, class or routine that could help me to load the XSD resorce into a XML schema object  and after having that XML schema, a way of validating the XML document.

The idea is to load the XML document (what I can easyly do), load the XML schema from a resource (what I can´t do so far), validate it againt a XML schema (what I can´t do either) and then finally processo the XML document.

Do any of you know how to accomplish that? I use Delphi 2007 for Win32.

Thanks in advance.
0
Utf
3/2/2009 5:43:32 PM
embarcadero.delphi.xml 291 articles. 0 followers. Follow

4 Replies
5255 Views

Similar Articles

[PageSpeed] 28

> {quote:title=MPS Informática wrote:}{quote}
> However, I need to validate XML documents saved as files against the very same XSD file I used in XML Data Bind wizard. So, I created a .rc file so I won´t need a XSD file to be released with my project.
> 

Here's some code that works using MSXML in Delphi.

{code}
unit XMLValidate;

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

interface

uses
  SysUtils, XMLIntf, xmldom, XMLSchema;

type
  EValidateXMLError = class(Exception)
  private
    FErrorCode: Integer;
    FReason: string;
  public
    constructor Create(AErrorCode: Integer; const AReason: string);
    property ErrorCode: Integer read FErrorCode;
    property Reason: string read FReason;
  end;

procedure ValidateXMLDoc(const Doc: IDOMDocument; const SchemaLocation, SchemaNS: WideString); overload;
procedure ValidateXMLDoc(const Doc: XMLIntf.IXMLDocument; const SchemaLocation, SchemaNS: WideString); overload;
procedure ValidateXMLDoc(const Doc: IDOMDocument; const Schema: IXMLSchemaDoc); overload;
procedure ValidateXMLDoc(const Doc: XMLIntf.IXMLDocument; const Schema: IXMLSchemaDoc); overload;

implementation

uses
  Windows, ComObj, msxmldom, MSXML2_TLB;

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

{ EValidateXMLError }

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

{ Utility routines }

function DOMToMSDom(const Doc: IDOMDocument): IXMLDOMDocument2;
begin
  Result := ((Doc as IXMLDOMNodeRef).GetXMLDOMNode as IXMLDOMDocument2);
end;

function LoadMSDom(const FileName: WideString): IXMLDOMDocument2;
begin
  Result := CoDOMDocument40.Create;
  Result.async := False;
  Result.resolveExternals := True; //False;
  Result.validateOnParse := True;
  Result.load(FileName);
end;

{ Validate }

procedure InternalValidateXMLDoc(const Doc: IDOMDocument; const SchemaDoc: IXMLDOMDocument2; const SchemaNS: WideString);
var
  MsxmlDoc: IXMLDOMDocument2;
  SchemaCache: IXMLDOMSchemaCollection;
  Error: IXMLDOMParseError;
begin
  MsxmlDoc := DOMToMSDom(Doc);
  SchemaCache := CoXMLSchemaCache40.Create;
  SchemaCache.add(SchemaNS, SchemaDoc);
  MsxmlDoc.schemas := SchemaCache;
  Error := MsxmlDoc.validate;
  if Error.errorCode <> S_OK then
    raise EValidateXMLError.Create(Error.errorCode, Error.reason);
end;

procedure ValidateXMLDoc(const Doc: IDOMDocument; const SchemaLocation, SchemaNS: WideString);
begin
  InternalValidateXMLDoc(Doc, LoadMSDom(SchemaLocation), SchemaNS);
end;

procedure ValidateXMLDoc(const Doc: XMLIntf.IXMLDocument; const SchemaLocation, SchemaNS: WideString);
begin
  InternalValidateXMLDoc(Doc.DOMDocument, LoadMSDom(SchemaLocation), SchemaNS);
end;

procedure ValidateXMLDoc(const Doc: IDOMDocument; const Schema: IXMLSchemaDoc);
begin
  InternalValidateXMLDoc(Doc, DOMToMSDom(Schema.DOMDocument), '');
end;

procedure ValidateXMLDoc(const Doc: XMLIntf.IXMLDocument; const Schema: IXMLSchemaDoc);
begin
  InternalValidateXMLDoc(Doc.DOMDocument, DOMToMSDom(Schema.DOMDocument), '');
end;

end.
{code}

Here's an example of using it, where XMLFileEdit.Lines.Text is the XML from a memo, and FSchemaFileName is the fully qualified path to your XSD (of course, it can also load the XML any other way, as long as it gets it into the XMLDocument):

{code}
  Doc := LoadXMLData(XmlFileEdit.Lines.Text);
  ValidateXMLDoc(Doc, FSchemaFileName, 'http://www.foo.com');
{code}
0
Ken
3/2/2009 9:12:54 PM
Hi MPS Informática,

> The idea is to load the XML document (what I can easyly do), load the XML schema from a resource (what I can´t do so far), validate it againt a XML schema (what I can´t do either) and then finally processo the XML document.

See http://www.drbob42.com/examines/examin76.htm for some information 
and approaches to validate an XML document. Basically, it can be done 
with the validateOnParse property of the MSXML.DOMDocument.

Groetjes,
           Bob Swart

-- 
Bob Swart Training & Consultancy (eBob42.com) Forever Loyal to Delphi
CodeGear Technology Partner -- CodeGear RAD Studio Reseller (BeNeLux)
Delphi Win32 & .NET books on Lulu.com: http://stores.lulu.com/drbob42
Personal courseware + e-mail support http://www.ebob42.com/courseware
Blog: http://www.drbob42.com/blog - RSS: http://eBob42.com/weblog.xml
0
Bob
3/3/2009 10:20:39 AM
Ken and Bob

Thank you so much for your assistance. Both answers are valuable info for me and will certainly make my life much easier.

Best regards,

Alex
0
Utf
3/3/2009 8:36:59 PM
Thank you so much for DOMToMSDOM. I have been looking all over for something like that so I could set a SelectionNamespaces property on my IXMLDocument
0
Robert
6/8/2010 5:30:14 AM
Reply:

Similar Artilces:

Validating XML file with XML schema
I want to be able to edit an XML file in browser. I open the XML file, read its contents and put it into a multi-line textbox for the user to edit it. Now, when the user wants to save the changes by pressing the save -button, I want to check if the XML data still is valid. For this I think the XML schema is perfect, right? Now, how can I write an function that takes a string parameter (which contains the whole XML file data from the textbox) and validates it against a schema file? I created the schema by passing a 100% valid XML file to the Visual Studio┬┤s "Create Schema" tool. The...

XML Schema not Validating XML Fragment
I'm trying to validate the following xml  fragment (Figure A.) against a schema document (Figure B.) that i have created and tested through a seperate XML Validator utility that so i know that the validation works outside of the asp.net code (Figure C.). The validation does return XML exceptions for well-formed stcructure but doesn't return any schema validation exceptions if i force an error in the xml. Any ideas why the XML fragment isn't being validated by the schema??? I've tried just about everything :( ========================= A. XML Fragment to Validate =========...

XMLParseFile: Validating XML File Against XML Schema
I am having problems using the XMLParseFile function to validate an XML file against an XML Schema generated by a source external to our organization. The XML file and XML Schema are stored locally in the same directory. Scenario as follows: 1. Schema received as an Email attachment from an outside source (i.e. external to our organization). 2. Attachment saved to disk: C:\myDirectory\schemaDoc.xsd 3. XML file generated from an external source datawindow using SaveAs method: C:\myDirectory\xmlDoc.xml 4. XMLParseFile first used to c...

Use an XML Schema to validate an XML files that contains includes.
Is there a way to validate an XML file that is made up by including several other XML files using an XML schema?     Yes, you need to set the included schemas with XmlSchema.Includes property. Pls take a look at: http://msdn2.microsoft.com/en-us/library/system.xml.schema.xmlschema.includes.aspxNOTE:If you find my response contains a reference to a third party World Wide Web site, I am providing this information as a convenience to you.Microsoft does not control these sites and has not tested any software or information found on these sites; therefore,Microsoft cannot make any...

Adding a XML schema to XML schema collection
I used SSEUtil to add a schema to my database but I am having problems.  Used these steps:SSEUtil -c> USE "c:\Rich.mdf"> GO>!RUN Resume.SQL//indicates success>SELECT * FROM SYS.XML_SCHEMA_COLLECTIONS>GO//schema not shown in list> USE master>GO>SELECT * FROM SYS.XML_SCHEMA_COLLECTIONS>GO//schema is shown in the queryIt appears that the schema is not added to the desired database, so when I try to use the schema in Visual Studio, the schema does not appear when I connect to the Rich.mdf database.  Any ideas on what I am doing wrong or why this might be happ...

XMl to XML
Hello,   I retrieved an XML from the dataset which retrieves data from the table in the database. I need to present the data  in a different structure. Is XSLT the way or are there any other options. please let me know. Thanks!! Yes XSLT is a good choice to convert xml file to other forms. You can take a look at XSLT Tutorial.Sincerely,Young Fang...

XML in, XML out
Hi All (and a happy holiday to those that will get a break), I am trying to read in an XML file of addresses. I need to remove all the address data from the file where code =~ /^000/ (there are none in the example data below). I need to reproduce that data 'as is', so I need to honour the tag structure, although the order of the tags doesn't need to be honoured. I have been trying to use XML::Simple and I had a go with XML::Smart but I haven't been able to get the results I want. My best effort is below (with XML::Simple). There are a couple of differences ...

write to a xml with a xml schema
Hi, I have a xml schema, and a xml that validate this schema.I want to append new nodes to this xml with code (c#)which is the best form to do this?thanks...

Xml schema to Xml file
Is it possible to convert xml schema to xml file.How can i do read&writexmlschema using a dataset with xml schema. I converted a xml file to xml schema in a web appliction project.Then what should be location of shema that i need to give for a dataset I mean dataset.readxmlscheme(server.mappath(??))   Please let me know I am new to this field     dataset.ReadXml(Server.MapPath("xml\ProductList.xml")) will read the xml as well as the schema of thexml file. no need to convert it into schema file while using dataset as it will automatically define the ...

XML & XML Schema
 Hi Can I use XML natively instead of a XML Schema.The schema is very simple and I would like to see if it's possible to use just XML. <!--W3C Schema generated by XMLSpy v2007 (http://www.altova.com)--> <!--Please add namespace attributes, a targetNamespace attribute and import elements according to your requirements--> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:import namespace="http://www.w3.org/XML/1998/namespace"/> <xs:element name="issue"> <...

Xml Schema from xml file
How should i create xml schema from xml file?  Do you mean an XSD?  That's easy--open the XML file in Visual Studio.  There will be a new XML menu button, and one option is to create an XSD.  If you have a lot of files, MS has a little tool at http://msdn.microsoft.com/en-us/vbasic/bb840042.aspx.If my post is your answer, please mark it as the answer. It will bring good karma.Crystal AllianceMy BlogFlorist Blogs  Thanks alot!!  It worked wonderfully...

Validate XML
I have some xml validation code that validates xml against an external schema. Problem is that it doesn't entirely work for some of the complex OTA (www.opentravel.org) xsd that I am trying to validate against. These schemas have multiple included schemas and refernces to other schemas and attribute groups. When I try to add one of these schemas to my schemacollection it errors out because it is unable to find some of the types defined in the included schemas. It seems to do fine going down one level to a referenced schema, but once that schema references another schema that is when I get...

Delphi 2006 XML Validation w/ XSD Schemas by Consuming ASMX Web Service
Utilizing Delphi 2006, is there a straight forward method of validating a CCD and/or CCR xml with a corresponding schema? Here are some samples which work at http://xreg2.nist.gov/cda-validation/mu.html: - http://www.selectayacht.com/validation/NoInfoNoErrors.xml - http://www.selectayacht.com/validation/SomeContentNoErrors.xml - http://www.selectayacht.com/validation/LotsofContentNoErrors.xml Here is a sample with four errors: - http://www.selectayacht.com/validation/4errors.xml I am unable to achieve the same results however attempting to perform validatio...

XML Schema that allows XML Fragments
I'm writing a little tool that would allow clients to create customizable profiles on my website. The profiles use a special XML language that will be parsed and transformed into an HTML document. A sample XML looks like this:   <websites> <header> <div class="company_websites"> </header> <content> <p> #SITE_NAME </p> </content> <footer> </div> </footer> </websites>  Most elements in the XML allow user to defi...

Web resources about - How to validate a IXMLDocument against a XML Schema? - embarcadero.delphi.xml

Resources last updated: 1/22/2016 8:51:31 PM