Monday, February 24, 2014

Xml file Validation class using Xsd file C# application

This is the validation method for xml file format and missing xml tags and missing xml values using xsd file.

When i want to import the xml config file in my application that time i want to validate my xml file format and

I just simple class use it. call the IsValidXml method and pass the xml file value and xsd file value.

If you don't need to xsd file source in your application my last post i have created the xsd file method just use it.


class Validations
    {
        private int nErrors = 0;
        private string strErrorMsg = string.Empty;
        public string Errors { get { return strErrorMsg; } }

        public bool IsValidXml(string xmlPath, string xsdPath)
        {
            bool bStatus = false;
            try
            {
                // Declare local objects
                XmlReaderSettings rs = new XmlReaderSettings();
                rs.ValidationType = ValidationType.Schema;
                rs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation |
                XmlSchemaValidationFlags.ReportValidationWarnings;
                //  Event Handler for handling exception & 
                //  this will be called whenever any mismatch between XML & XSD
                rs.ValidationEventHandler +=
            new ValidationEventHandler(ValidationEventHandler);
                rs.Schemas.Add(null, XmlReader.Create(xsdPath));
                //rs.Schemas.Add(CreateXSDSchemaValidationFormate());


                // reading xml
                using (XmlReader xmlValidatingReader = XmlReader.Create(xmlPath, rs))
                { while (xmlValidatingReader.Read()) { } }

                //Exception if error.
                if (nErrors > 0) { throw new Exception(strErrorMsg); }
                else { bStatus = true; }//Success
            }
            catch (Exception error) { bStatus = false; }

            return bStatus;
        }

        private void ValidationEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Warning) strErrorMsg += "WARNING: ";
            else strErrorMsg += "ERROR: ";
            nErrors++;

            if (e.Exception.Message.Contains("'Email' element is invalid"))
            {
                strErrorMsg = strErrorMsg + getErrorString
            ("Provided Email data is Invalid", "CAPIEMAIL007") + "\r\n";
            }
            if (e.Exception.Message.Contains
            ("The element 'Person' has invalid child element"))
            {
                strErrorMsg = strErrorMsg + getErrorString
            ("Provided XML contains invalid child element",
            "CAPINVALID005") + "\r\n";
            }
            else
            {
                strErrorMsg = strErrorMsg + e.Exception.Message + "\r\n";
            }
        }

        private string getErrorString(string erroString, string errorCode)
        {
            StringBuilder errXMl = new StringBuilder();
            errXMl.Append("<MyError> <errorString> ERROR_STRING </errorString> <errorCode> ERROR_CODE </errorCode> </MyError>");
            errXMl.Replace("ERROR_STRING", erroString);
            errXMl.Replace("ERROR_CODE", errorCode);
            return errXMl.ToString();
        }
}

No comments:

Post a Comment