views:

162

answers:

4

Hi,

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!

+3  A: 

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 }
stej
First - thank you.When trying to run your script: $xml = [xml]" 1 Apple 2 Orange " $orange = $xml.Fruits.Fruit | ? { [int]$_.Code -eq 2 } it throws an exception: "Error: Cannot find an overload for "XmlNode" and the argument count: "3"."Any idea?
rursw1
Hm, weird. Does `$xml.Fruits.Fruit` return anything?
stej
It's a long time ago I used V1, but I remember that this 'object like' accessing worked. There were some issues, but that won't apply to your example.
stej
+2  A: 

You can use XPath in V1 like this, if you prefer:

$xml = [xml](get-content $xmlFile)
$xml.SelectSingleNode("//Fruit[2]")

Code                                                        Name
----                                                        ----
2                                                           Orange
moerketh
A: 

Hi,

  1. I'm trying to run your simple script: $xml = [xml]" 1 Apple 2 Orange " $orange = $xml.Fruits.Fruit | ? { [int]$_.Code -eq 2 } But it throw exception: "Error: Cannot find an overload for "XmlNode" and the argument count: "3"."

    Do you have any idea what it can be?

  2. Actually, i want to get the Name of the selected ID - how you do that?

Thanks in advance!

avsg
This is not an answer - please add it as a comment below the answer you are referring to.
rursw1
A: 

So after all I moved to PowerShell 2. Thank you all!

rursw1