1

I have an xml file that will be read many times from the source code. I would like to know the efficient way in which i can read only once [ during application start ] the xml file and then cache its contents so that i can reuse it efficiently and fastly.

I am using C# 4. Kindly suggest the best practice for efficient caching and reading.

EDIT

Found this resource : CodeProject Article

I have loaded the xml file into an XmlDocument and Cached it using Enterprise Library as follows,

XmlDocument xdoc = new XmlDocument();
xdoc.Load("MyXmlFile.XML");
FileDependency fileDependency=new FileDependency("MyXmlFile.XML");
cacheManager.Add("XConfig", xdoc, CacheItemPriority.Normal, null, fileDependency);
Saravanan
  • 7,637
  • 5
  • 41
  • 72
  • possible duplicate of [Best practices to parse xml files?](http://stackoverflow.com/questions/55828/best-practices-to-parse-xml-files) – Neil Knight Feb 08 '12 at 13:23

2 Answers2

2

To read the xml is XmlReader, look: The most efficient way to parse Xml

And caching use a XmlDocument Object, and keep it in memory: C# Best way to hold xml data

To use both together, look: http://msdn.microsoft.com/en-us/library/a8ta6tz4.aspx

The problem with XmlDocument is to read, not to manipulate, the best way to manipulate is Linq to Xml, that has a good performance as well, but don't beat the XmlReader, look this comparisons: http://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html

Community
  • 1
  • 1
Vinicius Ottoni
  • 4,631
  • 9
  • 42
  • 64
  • I am trying to use the enterprise library caching and will get back to you after trying that. – Saravanan Feb 09 '12 at 04:45
  • :I have used enterprise library caching and the code is updated as part of the question. – Saravanan Feb 09 '12 at 05:38
  • 1
    You can use the XmlDocument to store file, but don't use to load. XmlDocument is the worst way to load xml files. Look to the fourth link that i pass to you. And about the enterprise library caching, it's a good one to use, because have a lot of things that you don't need to manage/create. – Vinicius Ottoni Feb 09 '12 at 11:51
  • I found minor difference between Linq-Xml and XmlDocument. However, i will check that one too. Anyways, Enterprise library comes to rescue for all cross cutting concerns. – Saravanan Feb 22 '12 at 07:40
2

This code will cache the document in a static, shared instance. This code is not thread safe, you didn't say whether that was a requirement:

private static XDocument _mydoc;
public static XDocument MyDoc 
{
   get 
   {
      return _mydoc ?? (_mydoc = XDocument.Parse("WellKnownXmlFile.xml");
   }
}
jlew
  • 10,491
  • 1
  • 35
  • 58
  • We should refresh the cache in case the file changes. also I would prefer to do this in a thread safe way. I will try EntLib Caching. will get back to you after testing. – Saravanan Feb 09 '12 at 04:46
  • I have used enterprise library caching and the code is updated as part of the question – Saravanan Feb 09 '12 at 05:39