Selecting specific nodes in an XML file from multiple levels
I have an xml file in a format similar to this:
<benchmark>
<group>
<id>1</id>
<rule>
<id>H1234</id>
<severity>High</severity>
</rule>
<title>How to win</title>
</group>
<group>
<id>2</id>
<rule>
<id>5317</id>
<severity>low</severit开发者_StackOverflow中文版y>
</rule>
<title>How to not</title>
</group>
<group>
<id>3</id>
<rule>
<id>H15678</id>
<severity>medium</severity>
</rule>
<title>How to be</title>
</group>
<group>
<id>4</id>
<rule>
<id>H454</id>
<severity>High</severity>
</rule>
<title>How to lose</title>
</group></benchmark>
I would like to be able to select the group/id, group/rule/id, group/rule/severity and group/title values from each group in the xml docoument.
I have tried this but it only gets me part of the way there:
I have tried $xml.benchmark.group | %{$_} | select title, id
I appreciate your help!
This works for me:
$xml.benchmark.group |
select @{ L = 'GroupID'; E = { $_.id } },
@{ L = 'GroupTitle'; E = { $_.title } },
@{ L = 'RuleID'; E = { $_.rule.id } },
@{ L = 'RuleSeverity'; E = { $_.rule.severity } }
yielding the following:
GroupID GroupTitle RuleID RuleSeverity
------- ---------- ------ ------------
1 How to win H1234 High
2 How to not 5317 low
3 How to be H15678 medium
4 How to lose H454 High
The syntax above is similar to SQL's SELECT Foo AS Bar
, selecting a value (Expression
or E
in the hashtable) and providing an alias for display purposes (Label
or L
in the hashtable).
This can be done with :
Clear-Host
$xmlData = [xml](Get-Content c:\temp\fic.xml)
foreach ($group in $xmlData.benchmark.group)
{
$group.id
$group.title
$group.rule.id
}
On the command line.
([xml](Get-Content C:\temp\fic.xmlfic.xml)).benchmark.group | % {$_.id + " " + $_.rule.id}
I hope it helps
JP
精彩评论