XML reading functionality : Schema « XML « C# / C Sharp

XML reading functionality


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Xml.Schema;

namespace AdvancementVoyage.Magic.Utility
    /// <summary>
    /// A helper class that provides common XML reading functionality.
    /// </summary>
    internal static class GenericXmlReaderHelper
        /// <summary>
        /// Validates data against the supplied schema and returns the desired
        /// collection of objects.
        /// </summary>
        /// <typeparam name="TTarget">The type of object being populated.</typeparam>
        /// <param name="parserFunc">The function responsible for translating the XML into objects.</param>
        /// <param name="schema">The schema that the XML stream will be validated against.</param>
        /// <param name="data">The actual xml data.</param>
        /// <returns>The collection of objects from the xml string.</returns>
        public static IList<TTarget> ReadTargetCollection<TTarget>(Func<XmlReader, IList<TTarget>> parserFunc, StringReader schema, StringReader data)
            var sc = XmlSchema.Read(schema, HandleValidationError);

            var settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;

            using (var reader = XmlReader.Create(data))
                return parserFunc(reader);

        /// <summary>
        /// The method that executes on a failed XML validation.
        /// </summary>
        /// <param name="src">
        /// The source of the event.
        /// </param>
        /// <param name="args">
        /// Arguments describing the cause of the failure.
        /// </param>
        private static void HandleValidationError(object src, ValidationEventArgs args)
            Trace.Fail(string.Format("Invalid data format: {0}", args.Message));


Related examples in the same category

1.Set XmlReaderSettings
2.Choose ValidationType
3.Validate an XML Document Against a Schema
4.Validate Schema
5.Use XML schema to validate XML documents
6.Use XmlReaderSettings to validate the Xml document
7.Strip Non Valid XML Characters.
8.Is Well Formed Xml
9.XmlSchema is an in-memory representation of an XML Schema
10.Is Xml Valid
11.Xml Validation Helper
12.Get Intrinsic Simple Types Names from System.Xml.Schema.DatatypeImplementation
13.Reads a XML schema file and returns the information found in that.