Hemi81
Hemi81

Reputation: 588

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'

Upvotes: 3

Views: 3656

Answers (3)

Esperento57
Esperento57

Reputation: 17472

other method:

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

Upvotes: 1

JPBlanc
JPBlanc

Reputation: 72630

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

Upvotes: 4

SomeShinyObject
SomeShinyObject

Reputation: 7801

You can try using XPath with SelectSingleNode:

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

Upvotes: 3

Related Questions