Determine XML Node Exists

powershell, powershell-2.0, xml

Solution

It appears that I was using the wrong syntax for SelectSingleNode. Here is a working example.

[xml]$xml = @'
<?xml version="1.0" encoding="UTF-8"?>
    <!-- Vendors we will send and retreive files from Get-Send means we will get a file and send them a file Send means we will only send them a file-->
    <Vendors>
        <Vendor Type="Get-Send">
            <Name>Vendor1</Name>            
            <RemotePath>/Remote/Path1/</RemotePath>
            <EncKey>pgpenc.key</EncKey>
        </Vendor>
        <Vendor Type="Send">
            <Name>Vendor2</Name>            
            <RemotePath>/Remote/Path2/</RemotePath> 
            <!-- This one has no EncKey -->         
        </Vendor>
    </Vendors>
'@

foreach ($vendor in $xml.Vendors.Vendor| Where-Object  {$_.Type -match "Send"}) {
    $NodeExists = $vendor.SelectSingleNode("./EncKey")
    if ($NodeExists -ne $null) {
        write-host "EncKey is null"
    }
    else {
       write-host "EncKey is not null"
    }
   }

EncKey is null
EncKey is not null

Thanks everyone for your help.

Problem

This is probably simple, but I'm trying to determine if a node exists in an XML document. I thought I found an answer in this post, How to check whether a node exists or not using powershell without getting exception?, but I didn't get it to work. This is my latest attempt. ``` foreach ($vendor in $xml.Vendors.Vendor| Where-Object {$_.Type -match "Send"}) { $NodeExists = $vendor.SelectSingleNode($vendor.EncKey) if ($NodeExists -ne $null) { # Do something } else { # something else } } ``` Edit Here is XML from my test file. I need to find out if EncKey exists or not for each vendor. ``` <?xml version="1.0" encoding="UTF-8"?> <!-- Vendors we will send and retreive files from Get-Send means we will get a file and send them a file Send means we will only send them a file--> <Vendors> <Vendor Type="Get-Send"> <Name>Vendor1</Name> <RemotePath>/Remote/Path1/</RemotePath> <EncKey>pgpenc.key</EncKey> </Vendor> <Vendor Type="Send"> <Name>Vendor2</Name> <RemotePath>/Remote/Path2/</RemotePath> <!-- This one has no EncKey --> </Vendor> </Vendors> ```

Original source

Related problems