Angleton
Angleton

Reputation: 79

XPath expression won't accept variable

Here is the sample code:

$xml = New-Object XML
$xml.load('C:\Users\Example\Desktop\examp.xml')

# this works
$node = $xml.selectSingleNode("//SERVER[@name='EXAMPLE']")

# this does not work
$t = 'EXAMPLE'
$node = $xml.selectSingleNode("//SERVER[@name=$t]")

Why? If you would like to see the XML as well, please say so.

Upvotes: 1

Views: 1938

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

Strings in XPath expressions must be enclosed in quotes (either single or double). As @MathiasR.Jessen pointed out in his comment to your question, your expression evaluates to //SERVER[@name=EXAMPLE] when it should be //SERVER[@name="EXAMPLE"] or //SERVER[@name='EXAMPLE']. The quotes in the expression

$t = 'EXAMPLE'

are simply for defining EXAMPLE as a string for PowerShell. They don't become part of the string and are thus not present when expanding the variable in the string with the XPath expression.

Demonstration:

PS C:\> $t = 'EXAMPLE'
PS C:\> $t
EXAMPLE
PS C:\> "//SERVER[@name=$t]"      # wrong
//SERVER[@name=EXAMPLE]
PS C:\> "//SERVER[@name='$t']"    # correct
//SERVER[@name='EXAMPLE']
PS C:\> "//SERVER[@name=`"$t`"]"  # correct
//SERVER[@name="EXAMPLE"]

Add the missing quotes to your XPath expression and the problem will disappear:

$node = $xml.selectSingleNode("//SERVER[@name='$t']")

Upvotes: 4

Related Questions