I continually hear people complaining about the performance of XPath queries in .NET, so I thought I would address it here. Most of the time, the problem is that people are using the wrong classes. (You know, with 6,000+ classes in .NET, I am always afraid that I will spend hours coding something just to find out that .NET provides it for free.) So, the trick here is to use the correct class. Don't perform XPath queries against an XMLDocument or an XMLDataDocument. Use an XPathDocument instead.
Data Layer Sample:
' create a command object to run the stored procedure
Command = New SqlCommand("uspEmployeeListXML",Connection)
Command.CommandType = CommandType.StoredProcedure
' open the connection
Connection.Open()
' create xml read to acces the xml
XmlRdr = Command.ExecuteXmlReader()
' move to the first content node,
' bypassing any schema, comments, etc.
XmlRdr.MoveToContent()
' populate xml XPath document
XPathDoc = New XPathDocument(XmlRdr)
' return the document
Return XPathDoc
ASP.NET Code-behind Sample:
' obtain an XML XPath Document
myXPathDoc = Data.GetXPathDoc
' create a Transform object to represent the XSLT stylesheet
myTransform = New XslTransform()
' load the stylesheet into the object
myTransform.Load(Server.MapPath("~/ManualXSLT.xslt"))
' transform the XML directly to the page
myTransform.Transform(myXPathDoc,Nothing, Response.Output, Nothing)
In one of my tests, an HTML page that took 30 seconds to render with an XMLDocument took 3 seconds with an XPathDocument.
For more examples of this kind of code, refer to my presentation entitled “XSLT & XPath”, found on the Memphis .NET Users Group Presentation page.