Schemas embedded as resources

Link. March 12, 2006. Comments [0]. Posted in: .NET | XML

Scott comments here on a utility XmlUrlResolver he wrote to load schemas embedded as resources in .NET assemblies that contain includes between them. This is a powerful feature, and it's nice to see how the XML stack was open to extension in ways like this.

FWIW, I did something like this a few years back (2002, actually) to load XSLTs embedded as resources for the original NUnitReport task for NAnt. Here's the code I wrote back then, which is pretty similar to Scott's code (except that I used an explicit URI schema):


/// <summary>

/// Loads the XSLT Transform

/// </summary>

/// <remarks>

/// This method will load the file specified

/// through the the xslfile attribute, or

/// the default transformation included

/// as a managed resource.

/// </remarks>

/// <returns>The Transformation to use</returns>

private XslTransform LoadTransform()

{

   XslTransform xslt = new XslTransform();

   if ( XslFile != null )

   {

      xslt.Load(XslFile);

   } else

   {

      XmlResolver resolver = new LocalResXmlResolver();

      Stream stream =

         (Stream)resolver.GetEntity(new Uri(XSL_DEF_FILE), null, null);

      XmlTextReader reader = new XmlTextReader(XSL_DEF_FILE, stream);

      xslt.Load(reader, resolver);

   }

   return xslt;

}

 

 

/// <summary>

/// Custom XmlResolver used to load the

/// XSLT files out of this assembly resources.

/// </summary>

internal class LocalResXmlResolver : XmlUrlResolver

{

   const string SCHEME_MRES = "mres";

 

   /// <summary>

   /// Loads the XSLT file

   /// </summary>

   /// <param name="absoluteUri"></param>

   /// <param name="role"></param>

   /// <param name="objToReturn"></param>

   /// <returns></returns>

   public override object GetEntity(Uri absoluteUri, string role, Type objToReturn)

   {

      if ( absoluteUri.Scheme != SCHEME_MRES )

      {

         // we don't know how to handle this URI scheme....

         return base.GetEntity(absoluteUri, role, objToReturn);

      }

      Assembly thisAssm = Assembly.GetExecutingAssembly();

      string filename = absoluteUri.Segments[absoluteUri.Segments.Length - 1];

      return thisAssm.GetManifestResourceStream(filename);

   }

 



Comments are closed.

Syndicate

About

Tomas Restrepo is a software developer located in Colombia, South America. His interests include .NET, Connected Systems, PowerShell and lately dynamic programming languages. More...

tomasrestrepo @ twitter My Flickr photostream My saved links on delicious My Technorati Profile

email: tomas@winterdom.com
msn: tomasr@passport.com

View my profile on LinkedIn

MVP logo

Ads


Links

Categories

Statistics

Total Posts: 1024
This Year: 94
This Month: 1
This Week: 2
Comments: 795

Blogroll

Archive

Other

Copyright © 2002-2008, Tomas Restrepo.

Powered by: newtelligence dasBlog 2.1.8139.823

Sign In