7

I am trying to check whether a particular node exists or not like follows.

In my config file there is a node named client ,it may or may not available.

If it is not available i have to add it.

    $xmldata = [xml](Get-Content $webConfig)    

        $xpath="//configuration/system.serviceModel"    
        $FullSearchStr= Select-XML -XML $xmldata -XPath $xpath

If ( $FullSearchStr -ne $null) {  

        #Add client node
        $client = $xmldata.CreateElement('Client')
        $client.set_InnerXML("$ClientNode")
        $xmldata.configuration."system.serviceModel".AppendChild($client) 
        $xmldata.Save($webConfig) 

    }

The condition i am checking may return array.

i would like to check whether the client node available before or not?

Samselvaprabu
  • 16,830
  • 32
  • 144
  • 230

3 Answers3

10

You can try the SelectSingleNode method:

$client = $xmldata.SelectSingleNode('//configuration/system.serviceModel/Client')

if(-not $client)
{
    $client = $xmldata.CreateElement('Client')
    ...
}
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
  • The condition succeeds even if 'client' node is there already – Samselvaprabu Oct 23 '12 at 13:45
  • If the xpath is passed as variable like this $xpath='//configuration/system.serviceModel/client' $client = $xmldata.SelectSingleNode($xpath) it fails , but if i pass the xpath directly then it works fine. Peculiar logic!!! what am i missing MVP? – Samselvaprabu Oct 23 '12 at 16:20
4

Why can't you just do something like:

$xmldata = [xml](Get-Content $webConfig)    
$FullSearchStr = $xmldata.configuration.'system.serviceModel'    
Andrey Marchuk
  • 13,301
  • 2
  • 36
  • 52
3

You can also use 'count' like a boolean

if ($xmldata.SelectSingleNode('//configuration/system.serviceModel/Client').Count)
{
 The count is 1 or more, so it exists
}
else
{
 The count is 0, so it doesn't exists
}
  • That has to be wrapped to get the count. `if (@($xmldata.SelectSingleNode('//configuration/system.serviceModel/Client')).Count -gt 0)` – StingyJack Oct 18 '17 at 13:14