以下将显示子元素,当且仅当它在第一个父元素中时才会显示。
$xml = @"
<?xml version="1.0" encoding="utf-8"?>
<root>
<par><commonchild>Hi there.</commonchild><otherchild>This is displayed.</otherchild></par>
<par><commonchild>Hi again.</commonchild><otherchild>So is this.</otherchild></par>
<par><commonchild>Well hello.</commonchild><missingchild>This is missing.</missingchild></par>
<par><commonchild>Cheers.</commonchild><missingchild>So is this.</missingchild></par>
</root>
"@
cls
Select-Xml -Content $xml -XPath "//par" | select -ExpandProperty node
输出
commonchild otherchild
----------- ----------
Hi there. This is displayed.
Hi again. So is this.
Well hello.
Cheers.
我们怎样才能显示所有父母的所有子元素?例如,以下工作但有时我们不知道所有子元素名称。
cls
Select-Xml -Content $xml -XPath "//par" |
select -ExpandProperty node |
select commonchild, otherchild, missingchild
输出
commonchild otherchild missingchild
----------- ---------- ------------
Hi there. This is displayed.
Hi again. So is this.
Well hello. This is missing.
Cheers. So is this.
答案 0 :(得分:3)
使用Format-Table
(ft)尝试选择要显示的属性:
C:\PS> Select-Xml -Xml $xml -XPath '/root//*' | % Node | ft name,'#text'
Name #text
---- -----
par
commonchild Hi there.
otherchild This is displayed.
par
commonchild Hi again.
otherchild So is this.
par
commonchild Well hello.
missingchild This is missing.
par
commonchild Cheers.
missingchild So is this.
Select -ExpandProperty <name>
用于扩展属性集合 - 将集合的项目展平为管道。虽然它也可以显示特定标量属性的值(作为一种副作用),但正如您所看到的,它并不总能正常工作。 : - )
答案 1 :(得分:3)
$pars = (Select-Xml -XPath "//par" -Content $xml) $childNodes = ($pars.Node.ChildNodes.Name | select -Unique) $pars.Node | select $childNodes commonchild otherchild missingchild ----------- ---------- ------------ Hi there. This is displayed. Hi again. So is this. Well hello. This is missing. Cheers. So is this.
所以XmlNode.ChildNodes
是一个隐藏属性,如果你在其上抛出Get-Member
参数,它只会被-Force
公开。基本上,我正在使用该属性来获取子节点的名称,然后对其进行过滤,因此我只使用select -Unique
命令中的每一个。然后,我将这些名称保存在名为$childNodes
的变量中,并将该变量用作最终-Property
上select
参数的值。