使用PowerShell遍历XML

时间:2018-08-28 13:31:48

标签: xml powershell

我正在尝试使用PowerShell遍历XML,但是无法获取InnerXML详细信息。

XML:

<script>
    <data>
        <address>
            <street>WhiteField</street>
            <zip>560100</zip>
            <city>Bangalore</city>
            <country>India</country>
            <postofficebox>BangaloreEast</postofficebox>
        </address>
    </data>
    <data>
        <address>
            <street>Gurgaon</street>
            <zip>601000</zip>
            <city>New Delhi</city>
            <country>India</country>
            <postofficebox>New Delhi West</postofficebox>
        </address>
    </data>
</script>

脚本:

[string]$FilePath = 'C:\Users\Sujeet\Desktop\UserData.xml'

try {
    [xml]$XMLInput = Get-Content -Path $FilePath
} catch {
    Write-Host "Failed to read or parse the XML File."
    exit
}

if ((Select-Xml -Xml $XMLInput -XPath "//address" | measure).Count -gt 0) {
    Select-Xml -Xml $XMLInput -XPath "//address" | foreach {
        $_.Node.InnerXML
    }
}

如何获取<street><city><country>的值?

我也想仅在城市为“班加罗尔”时获取详细信息。

2 个答案:

答案 0 :(得分:0)

InnerXml为您提供XML节点的内容作为字符串。如果要访问嵌套元素,请不要使用它。 $_.node是一个对象。可以像这样访问该对象的子节点:

Select-Xml -Xml $XMLInput -XPath '//address' | ForEach-Object {
    $street = $_.Node.street
    $city   = $_.Node.city
    ...
}

使用点访问会自动扩展节点的值。

要限制结果到特定城市,请在XPath表达式中添加一个过滤器:

$city = 'Bangalore'
Select-Xml -Xml $XMLInput -XPath "//address[city='${city}']" | ForEach-Object {
    $street = $_.Node.street
    $city   = $_.Node.city
    ...
}

或者,您可以使用SelectNodes()方法代替Select-Xml

$city = 'Bangalore'
$XMLInput.SelectNodes("//address[city='${city}']") | ForEach-Object {
    $street = $_.street
    $city   = $_.city
    ...
}

答案 1 :(得分:0)

这是另一种方法:

[xml]$xml = "<script>
    <data>
        <address>
            <street>WhiteField</street>
            <zip>560100</zip>
            <city>Bangalore</city>
            <country>India</country>
            <postofficebox>BangaloreEast</postofficebox>
        </address>
    </data>
    <data>
        <address>
            <street>Gurgaon</street>
            <zip>601000</zip>
            <city>New Delhi</city>
            <country>India</country>
            <postofficebox>New Delhi West</postofficebox>
        </address>
    </data>
</script>"

$addresses = $xml.script.data | Select-Object -ExpandProperty address
foreach ($address in $addresses) {
    if($address.city -eq 'Bangalore') {
        $address.street
    }
}