Powershell xml基于父节点选择节点';s信息
我正在编写一个powershell脚本,需要根据父节点的信息(属性名、id…)获取节点的一些值 例如:Powershell xml基于父节点选择节点';s信息,xml,powershell,foreach,Xml,Powershell,Foreach,我正在编写一个powershell脚本,需要根据父节点的信息(属性名、id…)获取节点的一些值 例如: <?xml version="1.0" encoding="UTF-8"?> <GrandParent> <Parent id="1"> <foo></foo> <bar></bar> <buzz></buzz> &
<?xml version="1.0" encoding="UTF-8"?>
<GrandParent>
<Parent id="1">
<foo></foo>
<bar></bar>
<buzz></buzz>
<Child Name="correct">
<Content>Value1</Content>
</Child>
<Child Name="wrong">
<Content>Value2</Content>
</Child>
<Child Name="wrong">
<Content>Value3</Content>
</Child>
</Parent>
<Parent id="2">
<foo></foo>
<bar></bar>
<buzz></buzz>
<Child Name="correct">
<Content>Value4</Content>
</Child>
<Child Name="wrong">
<Content>Value5</Content>
</Child>
<Child Name="wrong">
<Content>Value6</Content>
</Child>
</Parent>
<Parent id="3">
<foo></foo>
<bar></bar>
<buzz></buzz>
<Child Name="correct">
<Content>Value7</Content>
</Child>
<Child Name="wrong">
<Content>Value8</Content>
</Child>
<Child Name="wrong">
<Content>Value9</Content>
</Child>
</Parent>
</GrandParent>
PS:我是Powershell脚本的新手:(
有人能帮我写一个简单的脚本吗?以您为例:
[xml] $xml = Get-Content -Path .\test.xml
您可以获得所需的输出:
Parent 1: value1
Parent 2: value4
Parent 3: value7
像这样:
$Parents = @($xml.GrandParent.Parent)
for ($i = 0; $i -lt $Parents.Count; $i++) {
"Parent ${i}: " + @($Parents[$i].Child).Where{$_.Name -eq 'Correct'}.Content
}
或者使用ForEach对象
(没有注意到父对象有ID):
这不是最佳实践,但我喜欢它,因为它易于阅读
$xml = new-object -typename xml
$xml.Load("C:\temp\le.xml")
#To get stuff
$xml.GrandParent.Parent | Where-Object {$_.id -like 1}
#To edit stuff
($xml.GrandParent.Parent | Where-Object {$_.id -like 1}).foo = "test"
#To save stuff
$xml.Save("C:\temp\le.xml")
签出。您也看到了错误的东西。您的第一个
foreach
应该是$\uChild
,因为$\uCode>指的是父节点,然后您的第二个foreach
将指向该父节点中的每个子节点,这只是解释一下cit,因此我可以使用Where
数组方法。您也可以在要过滤的管道中将对象传递到Where object
:Where object Name-eq'Correct'
,而此代码可能会回答问题,提供有关如何以及为什么解决问题的附加上下文将提高答案的long term value.hmm有什么建议吗?@Xiakit建议是:添加关于如何以及为什么解决问题的附加上下文。这适用于您提供的所有答案(作为最佳实践)
$xml.GrandParent.Parent |
ForEach-Object {
"Parent $($_.id): " + @($_.Child).Where{$_.Name -eq 'Correct'}.Content
}
$xml = new-object -typename xml
$xml.Load("C:\temp\le.xml")
#To get stuff
$xml.GrandParent.Parent | Where-Object {$_.id -like 1}
#To edit stuff
($xml.GrandParent.Parent | Where-Object {$_.id -like 1}).foo = "test"
#To save stuff
$xml.Save("C:\temp\le.xml")