PowerShell: Retrieve a specific internal XML element

rkellerm picture rkellerm · May 26, 2010 · Viewed 13.9k times · Source

I have an XML document with this structure:

<Fruits>
    <Fruit>
        <Code>1</Code>
        <Name>Apple</Name>
    </Fruit>
</Fruits>

What is the best way to get a <Fruit> element by its code (or any other field) in PowerShell 1 code? (Not XPath, as it is supported in PowerShell 2 only)

Thanks!

Answer

stej picture stej · May 26, 2010

You can access the nodes like objects from Posh V1

$xml = [xml]"<Fruits>
    <Fruit>
        <Code>1</Code>
        <Name>Apple</Name>
    </Fruit>
    <Fruit>
        <Code>2</Code>
        <Name>Orange</Name>
    </Fruit>
</Fruits>"
$orange = $xml.Fruits.Fruit | ? { [int]$_.Code -eq 2 }