PermaLink ASP.Net LoadXml Doesn't Cache DTDs10/20/2009 07:32 PM
Seems like a bad oversight on MS' part.  Why would you want to read the DTD each time XmlDocument.LoadXml() is called? :-P
Someone was nice enough to write a caching XML resolver so you can save your bandwidth if you use LoadXml to parse files off a web site on nablesoft.

The actual code is:
public class CachedXmlResolver : XmlUrlResolver
   {
       
public override Uri ResolveUri(Uri baseUri, string relativeUri)
       {
           
if (relativeUri == "-//W3C//DTD XHTML 1.0 Strict//EN")
               
return new Uri("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");
           
else if (relativeUri == "-//W3C XHTML 1.0 Transitional//EN")
               
return new Uri("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");
           
else if (relativeUri == "-//W3C//DTD XHTML 1.0 Transitional//EN")
               
return new Uri("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");
           
else if (relativeUri == "-//W3C XHTML 1.0 Frameset//EN")
               
return new Uri("http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd");
           
else if (relativeUri == "-//W3C//DTD XHTML 1.1//EN")
               
return new Uri("http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd");
           
return base.ResolveUri(baseUri, relativeUri);
       }

       
public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
       {
           
if (!cache.ContainsKey(absoluteUri))
               GetNewStream(absoluteUri, role, ofObjectToReturn);
           
return new FileStream(cache[absoluteUri], FileMode.Open, FileAccess.Read, FileShare.Read);
       }

       
private void GetNewStream(Uri absoluteUri, string role, Type ofObjectToReturn) {
           
using (Stream stream = (Stream)base.GetEntity(absoluteUri, role, ofObjectToReturn))
           {
               String filename = System.IO.Path.GetTempFileName();
               
using (FileStream ms = new FileStream(filename, FileMode.Create, FileAccess.Write))
               {
                   Byte[] buffer =
new byte[8192];
                   Int32 count =
0;
                   
while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
                   {
                       ms.Write(buffer,
0, count);
                   }
                   ms.Flush();
                   cache.Add(absoluteUri, filename);
               }
           }
       }

       
public static Dictionary<Uri, String> cache = new Dictionary<Uri, String>();

   }

Comments :v
No comments.

Start Pages
RSS News Feed RSS Comments Feed CoComment Integrated
The BlogRoll
Calendar
November 2024
Su
Mo
Tu
We
Th
Fr
Sa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Search
Contact Me
About Ken
Full-stack developer (consultant) working with .Net, Java, Android, Javascript (jQuery, Meteor.js, AngularJS), Lotus Domino