none
XPATH query with a variable RRS feed

  • Question

  • Can a variable be used in an XPATH query?

    When I try the selectnodes query, where i use $var in the query below , I recieve this error;

    Exception calling "SelectNodes" with "2" argument(s): "XsltContext is needed for this query because of an unknown function."

    $cvenodes=$nvdxml.SelectNodes('//df:entry[.//vuln:references[@reference_type="VENDOR_ADVISORY"]][.//vuln:references/vuln:source[contains(., $var)]]',$nsmgr)

    If I replace $var with a hard coded string of what I'm looking for it works - I'm hoping to use a variable here instead. Is there a working example someplace showing how, if this is an option?

    Monday, January 19, 2015 1:54 AM

Answers

  • A good way to handle quotes:
    #
    # format string with variable
    $xpath="//df:entry[.//vuln:references[@reference_type='VENDOR_ADVISORY']][.//vuln:references/vuln:source[contains(.,'{0}')]]" -f $var
    
    $cvenodes=$nvdxml.SelectNodes($xpath,$nsmgr)
    
    #
    


    ¯\_(ツ)_/¯


    • Edited by jrv Monday, January 19, 2015 1:55 PM
    • Marked as answer by stamandk Monday, January 19, 2015 3:44 PM
    Monday, January 19, 2015 1:55 PM

All replies

  • variabkes donot expand inside of single quotes.

    $cvenodes=$nvdxml.SelectNodes("//df:entry[.//vuln:references[@reference_type='VENDOR_ADVISORY']][.//vuln:references/vuln:source[contains(., $var)]]",$nsmgr)


    ¯\_(ツ)_/¯

    Monday, January 19, 2015 4:19 AM
  • Ahhhh - thank you for the clarification.

    Regarding the expansion of variable, is there anything further needed? Reason I ask is, when I use the variable which contains the same string as when I hard code the string in the XPATH query, I do not receive the desired results - I only receive the 'VENDOR_ADVISORY' results.

    Monday, January 19, 2015 1:48 PM
  • Strings in XML are case sensitive.  XPath requires strings to be quoted.

    $var="'Some Vendor Name'"


    ¯\_(ツ)_/¯

    Monday, January 19, 2015 1:51 PM
  • A good way to handle quotes:
    #
    # format string with variable
    $xpath="//df:entry[.//vuln:references[@reference_type='VENDOR_ADVISORY']][.//vuln:references/vuln:source[contains(.,'{0}')]]" -f $var
    
    $cvenodes=$nvdxml.SelectNodes($xpath,$nsmgr)
    
    #
    


    ¯\_(ツ)_/¯


    • Edited by jrv Monday, January 19, 2015 1:55 PM
    • Marked as answer by stamandk Monday, January 19, 2015 3:44 PM
    Monday, January 19, 2015 1:55 PM
  • Thank you - $xpath fromat with variable worked perfectly
    Monday, January 19, 2015 3:44 PM
  • Using the formatter gets us out of issues with quotes and with amny variables being pasted into a string.

    ¯\_(ツ)_/¯

    Monday, January 19, 2015 3:45 PM