title: How do I get a list of child nodes from XML
body: <p>Given the following sample script (saved as <strong>sample.txt</strong> on my hard drive):</p>
  
  <pre><code>DECLARE @xVar XML
  SET @xVar = 
    '&lt;bookstore&gt;
        &lt;book&gt;
          &lt;title&gt;Writing Secure Code&lt;/title&gt;
          &lt;author&gt;
            &lt;first-name&gt;Michael&lt;/first-name&gt;
            &lt;last-name&gt;Howard&lt;/last-name&gt;
          &lt;/author&gt;
          &lt;author&gt;
            &lt;first-name&gt;David&lt;/first-name&gt;
            &lt;last-name&gt;LeBlanc&lt;/last-name&gt;
          &lt;/author&gt;
          &lt;price&gt;39.99&lt;/price&gt;
        &lt;/book&gt;
        &lt;book&gt;
          &lt;title&gt;Old Man and the sea&lt;/title&gt;
          &lt;author&gt;
            &lt;first-name&gt;Earnest&lt;/first-name&gt;
            &lt;last-name&gt;Hemmingway&lt;/last-name&gt;
          &lt;/author&gt;
          &lt;price&gt; 9.99&lt;/price&gt;
        &lt;/book&gt;
      &lt;/bookstore&gt;
      '
  
  SELECT nref.value('first-name[1]', 'nvarchar(50)') FirstName,
         nref.value('last-name[1]', 'nvarchar(50)') LastName
  FROM   @xVar.nodes('//author') AS R(nref)
  WHERE  nref.exist('.[first-name != "David"]') = 1
  </code></pre>
  
  <p>I want to extract the XML and determine if any child nodes have been added to node <strong>book</strong>.  For this use case, assume that <strong>author</strong> is the new node.</p>
  
  <p>I have written a script that works, but it seems grossly inefficient:</p>
  
  <pre><code>Set-StrictMode -Version Latest
  
  cls
  #The list of fields that I want to find
  [array]$expected_fields = "title", "price"
  
  #extract the xml from sample.txt and put it in an xml variable
  [string]$file_script = Get-Content "C:\PowerShellScripts\sample.txt"
  [int]$start_pos = $file_script.IndexOf("'") + 1
  [int]$end_pos = $file_script.SubString($start_pos + 1).IndexOf("'") + 1
  [xml]$xml_result = $file_script.SubString($start_pos,$end_pos)
  
  #NOTE:  THIS IS THE PART THAT FEELS WRONG
  #Convert the xml snipput into CSV file and then get the headers (which is the only thing I want)
  $export_file_name = "C:\PowerShellScripts\test.csv"
  Select-Xml 'child::bookstore/book' $xml_result  | Select-Object -expand Node | Export-Csv $export_file_name -NoTypeInformation -Delimiter:"`t" -Encoding:UTF8 
  [string]$field_names = Get-Content $export_file_name | Select-Object -first 1
  Remove-Item "C:\Users\Jennifer\Google Drive\PowerShellScripts\test.csv"
  [array]$found_fields = $field_names.Replace("""","").Split("`t")
  
  #report new fields
  foreach ($specific_field in $found_fields) {
      if ($expected_fields -notcontains $specific_field)
      {
          Write-Host "New field found:" $specific_field
      }
  }
  </code></pre>
  
  <p>Is there a better way to populate *$found_fields* rather than creating a CSV file, storing the first row in a variable and then deleting the CSV file?</p>