开发者

PowerShell: Retrieve a specific internal XML element

开发者 https://www.devze.com 2023-01-01 06:06 出处:网络
I have an XML document with this structure: <Fruits> <开发者_开发问答Fruit> <Code>1</Code>

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!


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 }


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

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

Code                                                        Name
----                                                        ----
2                                                           Orange
0

精彩评论

暂无评论...
验证码 换一张
取 消