2011-04-04 64 views
5

我有一個格式類似於這樣的XML文件:中選擇特定的節點在一個XML文件從多個層面

<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</severity> 
    </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> 

我希望能夠選擇組/ ID,組/規則/ ID ,xml文檔中每個組的組/規則/嚴重性和組/標題值。

我都試過,但它只是讓我的存在方式的一部分:

I have tried $xml.benchmark.group | %{$_} | select title, id 

我感謝您的幫助!

Clear-Host 
$xmlData = [xml](Get-Content c:\temp\fic.xml) 
foreach ($group in $xmlData.benchmark.group) 
{ 
    $group.id 
    $group.title 
    $group.rule.id 
} 

在命令行:

回答

11

這個工作對我來說:

$xml.benchmark.group | 
select @{ L = 'GroupID';  E = { $_.id } }, 
     @{ L = 'GroupTitle'; E = { $_.title } }, 
     @{ L = 'RuleID';  E = { $_.rule.id } }, 
     @{ L = 'RuleSeverity'; E = { $_.rule.severity } } 

產生如下:

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 

上面的語法類似於SQL的SELECT Foo AS Bar,在散列表中選擇一個值(ExpressionE)並提供用於顯示目的的別名(散列表中的LabelL)。

+0

這是有效的!謝謝! – jgrant 2011-04-04 16:39:22

2

這是可以做到的。

([xml](Get-Content C:\temp\fic.xmlfic.xml)).benchmark.group | % {$_.id + " " + $_.rule.id} 

我希望它能幫助

JP

+0

謝謝你的嘗試。我已經在拉ID和標題。我還需要來自較低級別節點的id和嚴重性。 – jgrant 2011-04-04 16:40:35

+0

在這裏,你並沒有做出太多的努力。我確實嘗試; o) – JPBlanc 2011-04-04 16:44:45

相關問題