A day with .Net

My day to day experince in .net

Validate an XML aganist an XSD Schema stored as embeded resource in a DLL

Posted by vivekcek on March 10, 2011

STEPS
—–

1.Add the schema to your library
2.Right click on the schmema file select properties set build action as embed resuorce.
3.Write a class XMLSchema in your library as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;
using System.Data;
namespace XMLParser
{
    public class XMLSchema
    {
        public bool ValidateXml(string xml,string xsdName)
        {
            try
            {
                //Declare a StreamReader and a StreamWriter
                StreamReader strmrStreamReader;
                //Extract the Resource using this line. Notice the namespace... ReadWriteResourceFromDLLorEXE!
                strmrStreamReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("XMLParser."+xsdName));
                //Here we are creating a new file in the Application Startup path, and for fun
                //we are also changing the name to NewFile.txt
                System.Xml.Schema.XmlSchema xSchema = new System.Xml.Schema.XmlSchema();
                xSchema = XmlSchema.Read(strmrStreamReader, null);
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas.Add(xSchema);
                settings.ValidationType = ValidationType.Schema;
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(xml);
                XmlReader rdr = XmlReader.Create(new StringReader(xDoc.InnerXml), settings);
                while (rdr.Read())
                { }
               
            }
            catch
            {
                return false;
            }
            return true;


        }
        public bool ValidateXml(XmlDocument xml)
        {
            return false;
        }
    }
}

4.Create an instance of the XmlSchema class and call the method ValidateXml() with your xml and,the name of XSD u add as resource in your dll

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s