Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3323464
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T23:18:21+00:00 2026-05-17T23:18:21+00:00

What is the easiest way for a Word macro to execute XPath expressions such

  • 0

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?

[1] http://msdn.microsoft.com/en-us/library/2c16b7x8.aspx

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T23:18:21+00:00Added an answer on May 17, 2026 at 11:18 pm

    You can use an XSL transform to evaluate XPath expressions, specifically xsl:value-of.

    I wrote an Evaluate function 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 that value-of returned 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, or String.

    Here are some tests I used to exercise the code. I used the books.xml file from the MSDN page you linked to (you’ll have to change the path to books.xml if you want to run these tests).

    Public Sub Test_Evaluate()
    
        Dim doc As New DOMDocument
        Dim value As Variant
    
        doc.async = False
        doc.Load "C:\Development\StackOverflow\XPath Evaluation\books.xml"
    
        Debug.Assert (doc.parseError.errorCode = 0)
    
        ' Sum of book prices should be a Double and equal to 30.97
        '
        value = Evaluate(doc, "sum(descendant::price)")
        Debug.Assert TypeName(value) = "Double"
        Debug.Assert value = 30.97
    
        ' Title of second book using text() selector should be "The Confidence Man"
        '
        value = Evaluate(doc, "descendant::book[2]/title/text()")
        Debug.Assert TypeName(value) = "String"
        Debug.Assert value = "The Confidence Man"
    
        ' Title of second book using string() function should be "The Confidence Man"
        '
        value = Evaluate(doc, "string(/bookstore/book[2]/title)")
        Debug.Assert TypeName(value) = "String"
        Debug.Assert value = "The Confidence Man"
    
        ' Total number of books should be 3
        '
        value = Evaluate(doc, "count(descendant::book)")
        Debug.Assert TypeName(value) = "Long"
        Debug.Assert value = 3
    
        ' Title of first book should not be "The Great Gatsby"
        '
        value = Evaluate(doc, "not(string(/bookstore/book[1]/title))='The Great Gatsby'")
        Debug.Assert TypeName(value) = "Boolean"
        Debug.Assert value = False
    
        ' Genre of second book should be "novel"
        '
        value = Evaluate(doc, "string(/bookstore/book[2]/attribute::genre)='novel'")
        Debug.Assert TypeName(value) = "Boolean"
        Debug.Assert value = True
    
        ' Selecting a non-existent node should generate an error
        '
        On Error Resume Next
    
        value = Evaluate(doc, "string(/bookstore/paperback[1])")
        Debug.Assert Err.Number = vbObjectError
    
        On Error GoTo 0
    
    End Sub
    

    And here is the code for the Evaluate function (the IsLong function 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 DOMDocument with a version-specific class name, such as DOMDocument30 (MSXML3) or DOMDocument60 (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.


    Public Function Evaluate(ByVal doc As DOMDocument, ByVal xpath As String) As Variant
    
        Static styleDoc As DOMDocument
        Dim valueOf As IXMLDOMElement
        Dim resultDoc As DOMDocument
        Dim result As Variant
    
        If styleDoc Is Nothing Then
    
            Set styleDoc = New DOMDocument
    
            styleDoc.loadXML _
                "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" & _
                    "<xsl:template match='/'>" & _
                        "<result>" & _
                            "<xsl:value-of />" & _
                        "</result>" & _
                    "</xsl:template>" & _
                "</xsl:stylesheet>"
    
        End If
    
        Set valueOf = styleDoc.selectSingleNode("//xsl:value-of")
        valueOf.setAttribute "select", xpath
    
        Set resultDoc = New DOMDocument
        doc.transformNodeToObject styleDoc, resultDoc
    
        If resultDoc.documentElement.childNodes.length = 0 Then
            Err.Raise vbObjectError, , "Expression '" & xpath & "' returned no results."
        End If
    
        result = resultDoc.documentElement.Text
    
        If IsLong(result) Then
            result = CLng(result)
        ElseIf IsNumeric(result) Then
            result = CDbl(result)
        ElseIf result = "true" Or result = "false" Then
            result = CBool(result)
        End If
    
        Evaluate = result
    
    End Function
    
    Private Function IsLong(ByVal value As Variant) As Boolean
    
        Dim temp As Long
    
        If Not IsNumeric(value) Then
            Exit Function
        End If
    
        On Error Resume Next
    
        temp = CLng(value)
    
        If Not Err.Number Then
            IsLong = (temp = CDbl(value))
        End If
    
    End Function
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

What is the easiest way to capitalize the first letter in each word of
.NET 4.0 I am looking for the easiest way to generate a Word document
The easiest way to think of my question is to think of a single,
What would be the easiest way to separate the directory name from the file
In TFS whats the easiest way of linking a backlog item to a large
Whats the best/easiest way to obtain a count of items within an IEnumerable collection
What's the easiest way to convert a percentage to a color ranging from Green
What would be the easiest way to be able to send and receive raw
What would be the easiest way to detach a specific JPA Entity Bean that
What is the easiest way to compare strings in Python, ignoring case? Of course

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.