Parsing XML with Powershell

I have a document xml

that I created from a Fortify validation. I currently have a document xml

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 this document and output the High, Medium and Low counts and assign them to a variable to navigate to another script.

My problem is when I pull the file xml

in powershell

, how do I get the score for high scores?

The script is currently:

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

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

      

+3


source to share


3 answers


Here's one way, when in 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's another way to create an object with three properties:

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

      



Finally, consider $a

:

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

      

so you can write: $a.High

+4


source


You can try using XPath with SelectSingleNode

:



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

      

+3


source


another method:

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

      

+1


source







All Articles