简体   繁体   中英

XML parsing with Powershell

I have an xml document that I have generated from a Fortify scan. Currently I have a xml doc that looks like this:

<Chart chartType="table">
    <Axis>Fortify Priority Order</Axis>
    <MajorAttribute>Analysis</MajorAttribute>
    <GroupingSection count="2">
        <groupTitle>High</groupTitle>
    </GroupingSection>
    <GroupingSection count="101">
        <groupTitle>Low</groupTitle>
    </GroupingSection>
    <GroupingSection count="5">
        <groupTitle>Medium</groupTitle>
    </GroupingSection>
</Chart>

What I want to do is parse through this doc and pull out the High , Medium , and Low counts and assign them to a variable to pass to another script.

My problem is when I pull the xml file into powershell , how do I get the count for High findings?

Currently script:

$xml = [xml](get-content $file)

$xml.GetElementsByTagName('groupTitle') | Select-Object -Property 'High'

Here is one way where at the end you will have 3 vars ( $high , $low , $medium ) :

$xml = [xml](get-content $file)
$xml.Chart.GroupingSection | % {Set-Variable -Name $_.groupTitle -Value $_.count}

Here is another way where you build an object with 3 properties :

$xml = [xml](get-content $file)
$xml.Chart.GroupingSection | % {$a=New-Object PSCustomObject}{Add-Member -InputObject $a -MemberType NoteProperty -Name $_.groupTitle -Value $_.count}

At the end consider $a :

High Low Medium
---- --- ------
2    101 5

so you can write : $a.High

您可以尝试将 XPath 与SelectSingleNode

$xml.SelectSingleNode("//groupTitle[text() = 'High']").ParentNode.Count

other method:

[xml] $xml=[xml](gc "c:\temp\file1.xml")
($xml.Chart.GroupingSection | where groupTitle -EQ "High").count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM