【发布时间】:2018-12-24 03:38:05
【问题描述】:
我正在编写一个 powershell 脚本,我需要根据父母的信息(属性名称、id ......)获取节点的一些值
例子:
<?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>
我想得到一些输出,例如: 父 1:值 1 父 2:值 4 父级 3:值 7
说明:对于每个父节点,我想查看具有“正确”名称的“子”节点并获取其子节点的值
我在 ForEach-Object 中使用 ForEach-Object 进行循环,但我的上下文“$_”总是指整个 xml 而不是当前范围:
$total_xml.GrandParent.Parent | ForEach-Oject {
$_.Parent.Child | ForEach-Object{
$_ #This refers back to the total_xml
}
}
PS:我是 Powershell 脚本的新手 :(
有人可以帮我写一个简单的脚本吗?
【问题讨论】:
-
查看the
-PipelineVariablecommon parameter。你也在看错误的东西。您的第一个foreach应该是$_.Child,因为$_指的是Parent节点,然后您的第二个foreach将指向该Parent内的每个Child节点。
标签: xml powershell foreach