Home > Mobile >  How to search (query) for particular element value insight XML? Powershell
How to search (query) for particular element value insight XML? Powershell

Time:07-30

How to search for particular xml attribute (descriptor) value across whole XML and return ID Protection values? I have this code:

$Xml = [xml]@'
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<TCXML xmlns="http://www.tcxml.org/Schemas/TCXMLSchema" format="low_level">

    <ToolDgnPart Protection="Restricted" id="169487" creation_date="2022-06-03T15:10:14Z"/>
    <Rel elemId="id1414" id="42432"/>
    <Form Protection="Restricted" id="2347890" creation_date="2022-06-03T15:10:14Z"/>
    <View Protection="Restricted" id="2342345" creation_date="2022-06-03T15:10:14Z"/>
    
</TCXML>
'@

$xml.TCXML.ToolDgnPart | Where-Object Protection -eq 'Restricted' | ForEach-Object {


[pscustomobject]@{
        ID = $_.id
        Protection = $_.Protection
    }
}

Powers shell is returning right value but only for one Attribute (ToolDgnPart) as designed:

ID     Protection
--     ----------
169487 Restricted

The goal is to make this proces generic to return all ID's values of all "Restricted" objects (ToolDgnPart, Rel, Form, View) without declaring each one as single line, ie:

$xml.TCXML.ToolDgnPart | Where-Object Protection -eq 'Restricted'
$xml.TCXML.Rel | Where-Object Protection -eq 'Restricted'
$xml.TCXML.Form | Where-Object Protection -eq 'Restricted'
$xml.TCXML.View | Where-Object Protection -eq 'Restricted'

THX in advance Mike

CodePudding user response:

You will need to use the XmlNode.SelectNodes Method to iterate through the child nodes:

$xml.TCXML.SelectNodes('*') |Where-Object Protection -eq 'Restricted'
Protection id      creation_date
---------- --      -------------
Restricted 169487  2022-06-03T15:10:14Z
Restricted 2347890 2022-06-03T15:10:14Z
Restricted 2342345 2022-06-03T15:10:14Z
  • Related