What is the easiest way for a Word macro to execute XPath expressions such as:
"string(/alpha/beta)"
"not(string(/alpha/beta)='true')"
which should return string and boolean respectively? (as opposed to an xml node or node list)
I want to avoid DLLs which won’t already be present on a machine running Office 2007 or 2010.
Function selectSingleNode(queryString As String) returns an IXMLDOMNode, so that won’t do.
In other words, something similar to .NET’s xpathnavigator.evaluate [1], which does this?
You can use an XSL transform to evaluate XPath expressions, specifically xsl:value-of.
I wrote an
Evaluatefunction that works on this principle. It creates a XSL stylesheet in memory which contains an XSL template that will take an XPath expression, evaluate it, and return a new XML document that contains the result in a<result>node. It checks to make sure thatvalue-ofreturned something (and throws an error if not), and if so, it converts the result of the XPath expression to one of the following data types:Long,Double,Boolean, orString.Here are some tests I used to exercise the code. I used the
books.xmlfile from the MSDN page you linked to (you’ll have to change the path tobooks.xmlif you want to run these tests).And here is the code for the
Evaluatefunction (theIsLongfunction is a helper function to make the data type conversion code a little more readable):Note: As barrowc mentions in the comments, you can be explicit about which version of MSXML you want to use by replacing
DOMDocumentwith a version-specific class name, such asDOMDocument30(MSXML3) orDOMDocument60(MSXML6). The code as written will default to using MSXML3, which is currently more widely-deployed, but MSXML6 has better performance and, being the latest version, is the one Microsoft currently recommends.See the question Which version of MSXML should I use? for more information about the different versions of MSXML.