3
votes

I am trying to select a value from a child node, based on attribute of the parent node (due to parent node has similar names). I need to get all values from a node based on parents attribute (ID).

So for each record, I need the corresponding VALUE (RECORD/FIELD/DATA/VALUE).

XML:

<PAGE id="8">
   <RECORD>
      <GUID>83704498-6ee6-4705-9280-0f0fe90e1148</GUID>
      <FIELD id="21">
         <DATA>
           <GUID>4a2bd78d-beab-4508-af76-0d14fe290709</GUID>
           <VALUE>Certificate 1</VALUE>
          </DATA>
      </FIELD>
      <FIELD id="22">
          <DATA>
              <VALUE>2015-01-20</VALUE>
          </DATA>
      </FIELD>
    <RECORD>
      <GUID>83704498-6ee6-4705-9280-0f0fe90e1148</GUID>
      <FIELD id="21">
         <DATA>
           <GUID>4a2bd78d-beab-4508-af76-0d14fe290709</GUID>
           <VALUE>Certificate 2</VALUE>
          </DATA>
      </FIELD>
      <FIELD id="22">
          <DATA>
              <VALUE>2015-01-20</VALUE>
          </DATA>
      </FIELD>
    </RECORD>
 </PAGE>

Powershell:

$record = $XML.SelectNodes('//PAGE/RECORD') | Select-Object @{'Name' = 'records' ; 'Expression' = { 
$_.FIELD.DATA.VALUE} }, GUID
$recordString = ($record | Out-String)
write-host $recordString

This output gives me the correct value and GUID, but i get values from all "FIELDS", but I only need value from field with attribute ID = 21.

1

1 Answers

3
votes

Use another XPath expression to target only the DATA nodes under FIELD with id=21:

$XML.SelectNodes('//PAGE/RECORD') | Select-Object @{
    'Name' = 'records'
    'Expression' = { 
        $_.SelectNodes('FIELD[@id="21"]/DATA/VALUE').innerText
    }
}, GUID