gpt4 book ai didi

xml - 使用powershell通过xml节点的嵌套循环

转载 作者:行者123 更新时间:2023-12-03 01:12:13 37 4
gpt4 key购买 nike

我想从一个XML文件中提取所有窗口节点和所有视点节点的名称属性值。

<?xml version='1.0' encoding='utf-8' ?>
<workbook>
<windows>
<window class='dashboard' name='D1'>
<viewpoints>
<viewpoint name='V1'> </viewpoint>
<viewpoint name='V2'> </viewpoint>
<viewpoint name='V3'> </viewpoint>
</viewpoints>
</window>
<window class='dashboard' name='D2'>
<viewpoints>
<viewpoint name='V10'> </viewpoint>
<viewpoint name='V11'> </viewpoint>
</viewpoints>
</window>
</windows>
</workbook>

这是我编写的代码:
[XML]$doc = get-content -path 'W:\Demo1.xml'


$objs = @()
$dashboards = $doc.SelectNodes("//window[@class = 'dashboard']")

foreach ($dashboard in $dashboards)
{
$worksheets = $dashboard.SelectNodes("//viewpoint[@name]")

foreach ($worksheet in $worksheets)
{
$obj = new-object psobject -prop @{Dashboard=$dashboard.name; Worksheet = $worksheet.name};
$objs += $obj;

}
}

$objs

我的期望:

仪表板工作表
D1 V1
D1 V2
D1 V3
D2 V10
D2 V11

我得到了:

仪表板工作表
D1 V1
D1 V2
D1 V3
D1 V10
D1 V11
D1 V14
D2 V1
D2 V2
D2 V3
D2 V10
D2 V11
D2 V14

怎么了结果与我对嵌套循环的工作原理的理解完全矛盾。

最佳答案

/字符开头的XPath意味着它将从文档根节点开始。要从上下文节点创建相对的XPath,需要在.之前放置/

因此,您的代码应为:

[XML]$doc = get-content -path 'W:\Demo1.xml'


$objs = @()
$dashboards = $doc.SelectNodes("//window[@class = 'dashboard']")

foreach ($dashboard in $dashboards)
{
$worksheets = $dashboard.SelectNodes(".//viewpoint[@name]")

foreach ($worksheet in $worksheets)
{
$obj = new-object psobject -prop @{Dashboard=$dashboard.name; Worksheet = $worksheet.name};
$objs += $obj;

}
}

$objs

关于xml - 使用powershell通过xml节点的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37315870/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com