Custom Search
Logiclabz
  • Home
  • Asp.Net
  • Loading XML from Application Cache in Asp.Net C# with file Dependancy

Loading XML from Application Cache in Asp.Net C# with file Dependancy

Normally in large site storing data on XML file would be essential.
Loading an large XML file on each visit would be time consuming.
Storing XML in Cache would help in improving the performance.
The cache thus made can be given CacheDependency to particular XML file thereby the cache would be reloaded when the content of the file changes.

Namespace Used: System.Xml

XmlDocument xoDoc = (Context.Cache["cachenameuniqueforeachxml"] != null) ? (XmlDocument)Context.Cache["cachenameuniqueforeachxml"] : null;
if (xoDoc == null)
  {
      xoDoc = new System.Xml.XmlDocument();
      string CfgFile = cfgFolder + "xmlfilename.xml";
      xoDoc.Load(CfgFile);
      Context.Cache.Add("cachenameuniqueforeachxml", xoDoc, new System.Web.Caching.CacheDependency(CfgFile), 
                System.DateTime.MaxValue, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null);
  }
      XmlElement xoEle = null;
      xoEle = (XmlElement)xoDoc.DocumentElement.SelectSingleNode("//CATEGORY[@categoryid='" + catid + "']");
      if (xoEle != null)
      {
           Response.Write(xoEle.GetAttribute("categoryname"));
      }

In above example, cache name "cachenameuniqueforeachxml" is checked which would be null at first time.
Hence "xmlfilename.xml" is loaded and Context.Cache.Add is use to add the XMLDOCUMENT in cache with System.Web.Caching.CacheDependency as the input file.
Required XMLELEMENT is queried using xmlpath and result node is obtained.
Going forward from second time "cachenameuniqueforeachxml" cache remains not null and XMLDOCUMENT is loaded from cache.
This would improve the performance inturn.



Leave a reply


Do you like this post?