Click here to Skip to main content
15,884,995 members
Articles / Programming Languages / XML

Parser Schemas– Easy and Powerful parsing of XML-based languages

Rate me:
Please Sign up or sign in to vote.
4.00/5 (5 votes)
18 Oct 20058 min read 53.1K   495   44  
An article on parsing XML files according to the specified schema.
/***********************************************************************\
 * Comnicate.CodeDom.Xml.ParserSchemas                                 *
 * Parses xml-based languages according to a user defined schema.      *
 * Copyright � 2005 Tomas Deml (as Comnicate!)                         *
 *                  tomasdeml@msn.com                                  *
 *                                                                     *
 * This library is free software; you can redistribute it and/or       *
 * modify it under the terms of the GNU Lesser General Public          *
 * License as published by the Free Software Foundation; either        *
 * version 2.1 of the License, or (at your option) any later version.  *
 *                                                                     *
 * This library is distributed in the hope that it will be useful,     *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of      *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU   *
 * Lesser General Public License for more details.                     *
\***********************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.XPath;
using System.Xml;
using Comnicate.CodeDom.Xml.ParserSchemas.Rules;
using Comnicate.CodeDom.Xml.ParserSchemas.Rules.Evaluated;
using Comnicate.CodeDom.Xml.ParserSchemas.Rules.Evaluation;

namespace Comnicate.CodeDom.Xml.ParserSchemas
{
    /// <summary>
    /// Represents the results of a schema evaluation.
    /// </summary>
    public class EvaluatedParserSchema : ParserSchema
    {
        #region Fields

        // Default namespace prefix
        private const string NamespacePrefix = "ns";

        // Evaluated parent rule
        private EvaluatedParentalRule evaluatedParentRule;

        #endregion

        #region .ctors

        /// <summary>
        /// Initializes a new instance of the <see cref="EvaluatedParserSchema"/> class.
        /// </summary>
        /// <param name="evaluatedParentNode">Evaluated parent node rule.</param>
        /// <param name="rawParentRule">Original (not evaluated) parent node rule.</param>
        private EvaluatedParserSchema(EvaluatedParentalRule evaluatedParentNode, ParentalRule rawParentRule) : base(rawParentRule)
        {
            // Check for null...
            if (evaluatedParentNode == null) throw new ArgumentNullException("evaluatedParentNode");

            // Init fields
            this.evaluatedParentRule = evaluatedParentNode;
            base.ParentNode = rawParentRule;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the evaluated parent rule. You can access its children using this property.
        /// </summary>
        public new EvaluatedParentalRule ParentNode
        {
            get
            {
                return this.evaluatedParentRule;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Evaluates the schema and return results.
        /// </summary>
        /// <param name="schema">Schema to evaluate.</param>
        /// <param name="documentNavigator">An instance of the <see cref="XPathNavigator"/> class representing the Xml document.</param>
        /// <param name="matchOption">Specifies if the <paramref name="documentNavigator"/> points to the parent node that will be matched by the <see cref="ParentNode"/> rule or if it points to the parent of the parent node that will be matched by the <see cref="ParentNode"/> rule.</param>
        /// <returns>Evaluation results as an instance of the <see cref="EvaluatedParserSchema"/> class.</returns>
        public static EvaluatedParserSchema EvaluateSchema(ParserSchema schema, XPathNavigator documentNavigator, ParentNodeMatchOption matchOption)
        {
            try
            {
                // Check args...
                if (schema == null) throw new ArgumentNullException("schema");
                if (documentNavigator == null) throw new ArgumentNullException("documentNavigator");
                if (!Enum.IsDefined(typeof(ParentNodeMatchOption), matchOption)) throw new ArgumentOutOfRangeException("matchOption");

                // If the provided schema was already evaluated...
                if (schema is EvaluatedParserSchema) throw new InvalidOperationException(Resources.ExceptionMsg_SchemaAlreadyEvaluated);

                // Make a copy of the document navigator (we do not want to change user's navigator)
                XPathNavigator ourDocumentNavigator = documentNavigator.Clone();

                // XmlNamespaceManager
                XmlNamespaceManager manager = null;

                // If the parent node is "namespaced"...
                if (schema.ParentNode.NamespaceUri != null)
                {
                    // Init XmlNamespaceManager according to the document to parse
                    manager = new XmlNamespaceManager(ourDocumentNavigator.NameTable);

                    // Add the namespace of the parent node
                    manager.AddNamespace(NamespacePrefix, schema.ParentNode.NamespaceUri.ToString());
                }

                // If the XPathNavigator already points to the parent node, point it to its parent...
                if (matchOption == ParentNodeMatchOption.NavigatorPointsToParentNode)
                    ourDocumentNavigator.MoveToParent();

                // Parent navigator
                XPathNavigator parentNavigator = null;

                // If we have to consider namaspaces...
                if (manager != null)
                    // Select a node with name and in namespace specified by the parent node rule
                    parentNavigator = ourDocumentNavigator.SelectSingleNode(String.Format("{0}:{1}", NamespacePrefix, schema.ParentNode.NodeName), manager);
                else
                    // Select a node with name specified by the parent node rule
                    parentNavigator = ourDocumentNavigator.SelectSingleNode(schema.ParentNode.NodeName);

                // No node matching to the parent node rule found...
                if (parentNavigator == null)
                    throw new ValidationException(String.Format(Resources.ExceptionMsg_Formatable1_ParentNodeNotFound, schema.ParentNode), schema.ParentNode, parentNavigator, null);

                // Evaluate the parent node rule (and its children)
                EvaluatedParentalRule evaluatedParentRule = schema.ParentNode.Evaluate(parentNavigator);

                // Construct the resulting schema
                EvaluatedParserSchema resultSchema = new EvaluatedParserSchema(evaluatedParentRule, schema.ParentNode);

                // Return evaluated schema
                return resultSchema;
            }
            catch (ValidationException vE)
            {
                throw new ValidationException(String.Format(Resources.ExceptionMsg_Formatable1_InvalidDocument, vE.Message), vE);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(String.Format(Resources.ExceptionMsg_Formatable1_SchemaCannotBeEvaluated, e.Message), e);
            }
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Czech Republic Czech Republic
I'm a student of the Low-voltage Electrical Engineering specialized on Computing from the Czech republic.

I'm a C# kind of guy, fan of .NET.

I've formed a programming group called 'Comnicate!'. Currently the only member of the group is myself. Wink | ;-)

Comments and Discussions