2014-01-22 87 views
2

下面将显示一个子元素,当且仅当它位于第一个父元素中时。Select-Xml仅显示第一个节点中的子节点

$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

明星是“任何” - 很可能是'/ * *? –

+0

@AlexeiLevenkov那不行。 –

+0

它不做什么? 'Select-Xml -Content $ xml -XPath“// *”'给你所有的节点......你只需要弄清楚如何处理它们,因为“all”包含'root'作为第一个节点,我认为它会混淆输出...尝试'/根// *'与您的原始代码有些非空输出 –

回答

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的变量中,并将该变量用作最终select上参数-Property上的值。

+0

这就是我想要的。谢谢。我想知道它将如何用非常大的(例如50 MB XML文件)执行。即在运行'select $ childnodes'之前,它可能必须先读取整个文件。 –

3

尝试它使用Format-Table(英尺)挑选出你想要显示的属性:

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>意味着展开属于集合性 - 展平收集的项目进入管道。虽然它也可以(作为一种副作用,我想)显示特定标量属性的值,正如您所看到的,它并不总是正常工作。 :-)

+0

这确实可以挑选出我想要显示的属性。然后,我可以通过'select property1,property2,property3'来使用特定的投影。 @ Nacimota的答案更多是我想要的,因为它避免了对特定投影的需求。 –

相关问题