I'm having a XML similar to following and need to get <Document>
nodes where<ZZXMLT>
equals '04'.
<DataArea>
<Document>
<ZZPRTF>PMS241PF</ZZPRTF>
<ZZXMLT Label="Variant">03</ZZXMLT>
</Document>
<Document>
<ZZPRTF>PMS241PF</ZZPRTF>
<ZZXMLT Label="Variant">04</ZZXMLT>
</Document>
<Document>
<ZZPRTF>PMS242PF</ZZPRTF>
<ZZXMLT Label="Variant">04</ZZXMLT>
</Document>
</DataArea>
Following is the powershell code.
$xml = [xml](Get-Content -Path $file.FullName | Out-String)
$product = $xml.SelectSingleNode("//Document")
$parent = $product.ParentNode
$allproducts = @($parent.SelectNodes("Document") | Where-Object {$_.ZZXMLT -eq "04"})
This is working fine when <ZZXMLT>
does not have an attribute but for the original XML there is an attribute.
Can somebody help me to get this done
Thank you!
CodePudding user response:
You don't need Where-Object
for this - you can describe a <Document>
node with a descendant <ZZXMLT>
node with the text contents 04
in the XPath expression passed to SelectNodes
:
$allproducts = $xml.SelectNodes("/DataArea/Document[./ZZXMLT[text()='04']]")
CodePudding user response:
Using PowerShell's Xml dot-notation and the Where-Object
cmdlet:
$Xml = [xml]@'
<DataArea>
<Document>
<ZZPRTF>PMS241PF</ZZPRTF>
<ZZXMLT Label="Variant">03</ZZXMLT>
</Document>
<Document>
<ZZPRTF>PMS241PF</ZZPRTF>
<ZZXMLT Label="Variant">04</ZZXMLT>
</Document>
<Document>
<ZZPRTF>PMS242PF</ZZPRTF>
<ZZXMLT Label="Variant">04</ZZXMLT>
</Document>
</DataArea>
'@
$Xml.DataArea.Document |Where-Object { $_.ZZXMLT.'#Text' -eq '04' }
ZZPRTF ZZXMLT
------ ------
PMS241PF ZZXMLT
PMS242PF ZZXMLT