代码之家  ›  专栏  ›  技术社区  ›  rkellerm

PowerShell:检索特定的内部XML元素

  •  2
  • rkellerm  · 技术社区  · 16 年前

    我有一个结构如下的XML文档:

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

    <Fruit> 元素的代码(或任何其他字段)? (不是XPath,因为它仅在PowerShell 2中受支持)

    2 回复  |  直到 16 年前
        1
  •  3
  •   moerketh    16 年前

    如果您愿意,可以在V1中这样使用XPath:

    $xml = [xml](get-content $xmlFile)
    $xml.SelectSingleNode("//Fruit[2]")
    
    Code                                                        Name
    ----                                                        ----
    2                                                           Orange
    
        2
  •  5
  •   stej    16 年前

    $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 }