Create an xml file as show below, but with 10000 contact elements called as “address_xw_n.xml” and make it available in D driver (d:\).
<AddressBook>
<Contact>
<Name>Person1</Name>
<Address1><![CDATA[Number101]]></Address1>
<Address2><![CDATA[Address501]]></Address2>
<Zip>50001</Zip>
<Phone><![CDATA[999991]]></Phone>
</Contact>
</AddressBook>
The below code demonstrate the time take to query the above created xml file using xpath and LINQ for the Phone element value “999999996“.using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Diagnostics;
using System.Xml.Linq;
namespace QueryXML
{
class Program
{
static void Main(string[] args)
{
Stopwatch objSW = null;
String strNormalFilePath;
strNormalFilePath = @"d:\address_xw_n.xml";
XmlDocument xmlNDoc;
xmlNDoc = new XmlDocument();
XDocument xNDoc;
objSW = new Stopwatch();
objSW.Reset();
objSW.Start();
//load the xml
xmlNDoc.Load(strNormalFilePath);
//xml query using xpath - Normal format
objSW.Reset();
objSW.Start();
XmlNode xmlQNNode = xmlNDoc.SelectSingleNode(
"/AddressBook/Contact/Phone[contains(text(),'999999996')]");
//Console.WriteLine(xmlQNNode.Name +
// "-" + xmlQNNode.ChildNodes[0].Value);
objSW.Stop();
Console.WriteLine("XML query using xpath - Normal format");
Console.WriteLine("TimeElapsed (Stopwatch float):{0}ms",
objSW.Elapsed.TotalMilliseconds);
Console.WriteLine("TimeElapsed (Stopwatch rounded):{0}ms",
objSW.ElapsedMilliseconds);
//xml query using LINQ - Normal format
//Let us not include the conversion of XmlDocument to XDocument
xNDoc = XDocument.Parse(xmlNDoc.OuterXml);
objSW.Reset();
objSW.Start();
var linqNQuery = from p in
xNDoc.Root.Elements("Contact").Elements("Phone")
where p.Value.Contains("999999996") select p;
/*foreach (XElement e in linqNQuery)
{
Console.WriteLine(e.Name+"-"+e.Value);
}*/
objSW.Stop();
Console.WriteLine("XML query using LINQ - Normal format");
Console.WriteLine("TimeElapsed (Stopwatch float):{0}ms",
objSW.Elapsed.TotalMilliseconds);
Console.WriteLine("TimeElapsed (Stopwatch rounded):{0}ms",
objSW.ElapsedMilliseconds);
Console.ReadLine();
}
}
}
Output: XML query using xpath - Normal format TimeElapsed (Stopwatch float):20.0936ms TimeElapsed (Stopwatch rounded):20ms XML query using LINQ - Normal format TimeElapsed (Stopwatch float):0.5082ms TimeElapsed (Stopwatch rounded):0ms
Rule: Use LINQ for querying xml content.