Home > Data Management, MS CRM, XML > Fetch Xml in-memory validation

Fetch Xml in-memory validation

If you need to validate Fetch Xml (or any xml as well) without any external files like .xsd schema, you may find the following code usefull:

        public static Boolean ValidateFetchXml(string fetchxml)
        {
            var reader = new XmlValidatingReader(fetchxml, XmlNodeType.Document, null);
            reader.ValidationType = ValidationType.Schema;
            XmlReader xr = null;
            xr = XmlReader.Create(new MemoryStream(Encoding.Default.GetBytes(schemaText)));
            var schemaCollection = new XmlSchemaCollection();
            schemaCollection.Add(null, xr);
            reader.Schemas.Add(schemaCollection);

            bool isValid = true;
            reader.ValidationEventHandler += ((o, e) => isValid = false);
            reader.Read();

            XmlDocument doc = new XmlDocument();
            try
            {
                doc.LoadXml(fetchxml);
            }
            catch (Exception ex)
            {
                isValid = false;
            }

            return isValid;
        }

Note, that schema name is already loaded into schemaText variable. Its text can be found in CRM SDK in \sdk\server\schemas\fetch.xsd file. As soon as I use it in static class, I’ve made it constant, but you can provide it to method parameters if you will hame different schemas for validation.

Xml-completeness (closed tags) are verified by trying to create XmlDocument. If there are any unclosed tags, it will throw error.

Advertisements
Categories: Data Management, MS CRM, XML Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: