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.Schemas.Add(sc);
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