【问题标题】:Parsing xml using powershell使用powershell解析xml
【发布时间】:2013-08-04 14:59:18
【问题描述】:

我是PowerShell的新手。我有一个配置 XML,其内容为 -

<xml>
    <Section name="BackendStatus">
        <BEName BE="crust" Status="1" />
        <BEName BE="pizza" Status="1" />
        <BEName BE="pie" Status="1" />
        <BEName BE="bread" Status="1" />
        <BEName BE="Kulcha" Status="1" />
        <BEName BE="kulfi" Status="1" />
        <BEName BE="cheese" Status="1" />
    </Section>
</xml>

我需要解析BEName 中的每个元素以检查状态。这如何使用 PowerShell 完成?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    第一步是将你的 xml 字符串加载到一个 XmlDocument 中,使用 powershell 的 将字符串转换为 [xml] 的独特能力

    $doc = [xml]@'
    <xml>
        <Section name="BackendStatus">
            <BEName BE="crust" Status="1" />
            <BEName BE="pizza" Status="1" />
            <BEName BE="pie" Status="1" />
            <BEName BE="bread" Status="1" />
            <BEName BE="Kulcha" Status="1" />
            <BEName BE="kulfi" Status="1" />
            <BEName BE="cheese" Status="1" />
        </Section>
    </xml>
    '@
    

    Powershell 使得使用点符号解析 xml 变得非常容易。这 语句将为您的 BEName 元素生成一系列 XmlElements:

    $doc.xml.Section.BEName
    

    然后您可以将这些对象通过管道传递到 where-object cmdlet 以过滤 结果。您可以使用 ?作为 where 的快捷方式

    $doc.xml.Section.BEName | ? { $_.Status -eq 1 }
    

    大括号内的表达式将为 管道,只有那些状态为 1 的才会被返回。 $_ 运算符引用管道中的当前对象(一个 XmlElement)。

    如果您需要为管道中的每个对象做一些事情,您可以通过管道 对象放入 foreach-object cmdlet,它为每个对象执行一个块 在管线中。 % 是 foreach 的快捷方式:

    $doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }
    

    Powershell 在这方面做得很好。组装管道真的很容易 对象,过滤管道,并对管道中的每个对象进行操作。

    【讨论】:

    • 请注意,通过点遍历获取标签将为不包含子标签的任何父标签返回空对象。例如。对于上面的示例,$doc.xml.Section.BEName.BEChild.Length 将是 7,尽管没有定义 BEChild 标记。如果您正在过滤,这不会成为问题,但如果您通过 ForEach-Object 或类似方式进行迭代,则需要安全地跳过这些空对象。
    【解决方案2】:

    如果你想从一个文件开始,你可以这样做

    [xml]$cn = Get-Content config.xml
    $cn.xml.Section.BEName
    

    Use PowerShell to Parse an XML File

    【讨论】:

    • 链接已损坏 :-(
    【解决方案3】:
    [xml]$xmlfile = '<xml> <Section name="BackendStatus"> <BEName BE="crust" Status="1" /> <BEName BE="pizza" Status="1" /> <BEName BE="pie" Status="1" /> <BEName BE="bread" Status="1" /> <BEName BE="Kulcha" Status="1" /> <BEName BE="kulfi" Status="1" /> <BEName BE="cheese" Status="1" /> </Section> </xml>'
    
    foreach ($bename in $xmlfile.xml.Section.BEName) {
        if($bename.Status -eq 1){
            #Do something
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 1970-01-01
      • 2019-09-27
      • 2021-01-02
      • 2020-12-30
      • 2010-12-15
      • 2020-10-22
      相关资源
      最近更新 更多