All pastes #111571 Raw Edit

atsushieno

public text v1 · immutable
#111571 ·published 2006-08-02 12:05 UTC
rendered paste body
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Xml;

namespace Mono.Xml
{
	/*
	public class Test
	{
		public static void Main (string [] args)
		{
			DiscoXmlResolver r = new DiscoXmlResolver (args [0]);
			foreach (string url in r.Map.Keys)
				Console.WriteLine ("{0} -> {1}", url, r.Map [url]);
		}
	}
	*/

	public class DiscoXmlResolver : XmlResolver
	{
		Hashtable map = new Hashtable ();
		XmlResolver default_resolver = new XmlUrlResolver ();
		string base_path;

		public DiscoXmlResolver (string discomap)
		{
			base_path = Path.GetDirectoryName (discomap);
			XmlReader r = new XmlTextReader (discomap);
			try {
				Init (r);
			} finally {
				r.Close ();
			}
		}

		public DiscoXmlResolver (XmlReader discomap)
		{
			if (discomap.BaseURI != "") {
				Uri uri = new Uri (discomap.BaseURI);
				if (uri.IsFile)
					base_path = Path.GetDirectoryName (uri.LocalPath);
			}
			Init (discomap);
		}

		void Init (XmlReader discomap)
		{
			discomap.MoveToContent ();
			discomap.ReadStartElement ("DiscoveryClientResultsFile");
			discomap.MoveToContent ();
			discomap.ReadStartElement ("Results");
			discomap.MoveToContent ();
			while (discomap.NodeType == XmlNodeType.Element) {
				string file = discomap.GetAttribute ("filename");
				string url = discomap.GetAttribute ("url");
				discomap.Skip ();
				discomap.MoveToContent ();
				map [new Uri (url).AbsoluteUri] = Path.Combine (base_path, file);
			}
		}

		public override ICredentials Credentials {
			set { throw new NotSupportedException (); }
		}

		public IDictionary Map {
			get { return map; }
		}

		public XmlResolver DefaultResolver {
			set { default_resolver = value; }
		}

		public override object GetEntity (Uri absoluteUri, 
			string role, Type type)
		{
			if (type != typeof (Stream))
				throw new NotSupportedException (String.Format ("Type {0} is not supported.", type));

			string file = map [absoluteUri.AbsoluteUri] as string;
			if (file != null)
				return File.OpenRead (file);
			if (default_resolver == null)
				throw new NotSupportedException (String.Format ("The discomap resolver couldn't resolve '{0}' and there is no more resolver to use.", absoluteUri));
			return default_resolver.GetEntity (absoluteUri, role, type);
		}
	}
}