Search in XML Node

I have this Sample XML Code. I want to run through every “testdata” and check if there is a “import” with the source “api”. When yes, save the complete import node in a new variable.

I am grateful for any help, suggestion or solution.

Bahnski

Clear-Host
$XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<mydata>
    <testdata>
        <id>1</id>
        <feld1>Feld1</feld1>
        <imports>
            <import>
                <source>Web</source>
                <data>1111111</data>
            </import>
            <import>
                <source>API</source>
                <data>2222222</data>
            </import>
        </imports>
    </testdata>
    <testdata>
        <id>2</id>
        <feld1>Feld2</feld1>
        <imports>
            <import>
                <source>Web</source>
                <data>2222222222</data>
            </import>
        </imports>
    </testdata>
    <testdata>
        <id>3</id>
        <feld1>Feld3</feld1>
        <imports>
            <import>
                <source>API</source>
                <data>3333333</data>
            </import>
        </imports>
    </testdata>
</mydata>'

$myXML = New-Object -TypeName System.Xml.XmlDocument
$myXML =[xml]$XML

foreach ($Testdata in $myxml.mydata.testdata){
       
}

It looks like you need to have nested foreach loops to get down to the individual imports. Something like this maybe?

$Result = foreach ($Testdata in $myxml.mydata.testdata) {
    foreach ($import in $Testdata.imports.import) {
        If ($import.source -eq "API") {
            $import
        }
    }
}

It looks so easy. Why didn´t I find this easy way. Thank you

Where-Object can also be used:

$myXML.mydata.testdata.imports.import | 
    Where-Object { $_.Source -eq 'API' }