I have an application in which I am using XPathNavigator to iterate nodes. It is working fine.
But I want to know that if I use LINQ to Xml....
What benefits(Performance, maintainability) I will get?
With XPath, LINQ to Xml what is the performance hit?
I am using C#.net, VS 2010 and my .xml is mid size.
Just to add onto what has already been stated here, overall performance seems to depends on what you are actually doing with the document in question. This is what I have concluded based on a simple experimental run comparing parsing performance between XElement to XPathNavigator.
If you are selecting nodes, traversing these nodes and reading some attribute values:
On the other hand, if you are also reading the value of each node's children it gets a little interesting:
These conclusions are based on the following code:
with books.xml downloaded from here
Overall, it looks like the XElement parsing API, excluding the XPath extensions, gives you the best performance, while also easier to use, if your document is somewhat flat. If you have deep nested structures where you have to do something like
then XElement.XPathSelectElement may provide the best compromise between performance and code maintainability.
Well,
XPathNavigator
will generally be faster thanLinq to XML
queries. But there's always 'but'.Linq to XML
will definitely make your code more readable and maintainable. It's easier (at least for me) to read linq query then analyze XPath. Also - you will get intellisense when writing query which will help to make your code correct.Linq to XML
also gives you possibility to easily modify data, if that's what you need.XPathNavigator
gives you readonly access.On the other hand, if you really need top performance,
XPathNavigator
is probably the way to go. It simply depends on your current scenario and what you're trying to accomplish. If performance is not an issue (XML file is rather small, you won't make many requests to this file and so on) you can easily go withLinq to XML
. Otherwise stick close toXPathNavigator
.