Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

XML Validation 1

Status
Not open for further replies.

SiJP

Programmer
May 8, 2002
708
0
0
GB
I've created a C# dll (for com interop) that is called from a VB based application (sorry guys, yep I'm a VB programmer!)

From VB, the following call is made:

sErrors = myobj.Validate(sXMLFile, arrXSD)

- myobj is latebound object for the class
- sXMLFile is a string that contains the location of our xml file that needs to be validated.
- arrXSD contains an array of XSD's that the XML file is validated against.

I need the C# 'Validate' function to do the following:

1) Add each of the schema's in the array into the XmlValidatingReader object
2) Validate the XML file based on the schema's, adding any errors into a new XML file (called whatever you like)
3) The Validate function should return the path to the new XML file that contains the error.

Some guidance on how to achieve the three points above would be awesome!

------------------------
Hit any User to continue
 
I don't now what is your myObj but try this code that work for me:
Code:
		static string ErrorMessage = "";
		static int ErrorsCount = 0;

		public static bool ValidateXml(ref string ReturnMessage, string xmlFile, string xsdFile)
		{
			try
			{
				ErrorMessage = "";
				// Declare local objects
				XmlTextReader         tr   = null;
				XmlTextReader		trs	= null;
				XmlSchemaCollection   xsc  = null;
				XmlValidatingReader   vr   = null;

				// Text reader object
				tr  = new XmlTextReader(xmlFile);
				trs = new XmlTextReader(xsdFile);
				xsc = new XmlSchemaCollection();
				xsc.Add(null, trs);

				// XML validator object

				vr = new XmlValidatingReader(tr);

				vr.Schemas.Add(xsc);

				// Add validation event handler

				vr.ValidationType = ValidationType.Schema;
				vr.ValidationEventHandler +=
					new ValidationEventHandler(ValidationHandler);

				// Validate XML data

				while(vr.Read());

				vr.Close();

				// Raise exception, if XML validation fails
				if (ErrorsCount > 0)
				{
					ReturnMessage += "Validation failled" + Environment.NewLine + "Error: " + ErrorMessage + Environment.NewLine;
					return false;
				}
				return true;
			}
		}

		private static void ValidationHandler(object sender, ValidationEventArgs args)
		{
			ErrorMessage = ErrorMessage + args.Message + Environment.NewLine;
			ErrorsCount ++;
		}
 
Bobisto.. that's given me a good heads up .. cheers!

(fyi myObj in vb is basically a late bound object tat is set for the class e.g. Set myObj = CreateObject("myDLL.ClassName"))

------------------------
Hit any User to continue
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top