title: Check if XML node exists - Loop not finding node if its available
body: <p>I have an XML file were some records have certain nodes/elements missing (information needed for import into table). If a certain node is missing for that record then I set a default value and move on the next record. In the sample XML file, Product A has no Barcode node so generate that value based on other information, Product B has all the nodes required so all values are taken from the nodes.</p>
  
  <pre><code>&lt;ProdExtract&gt;
  &lt;Product&gt;
      &lt;BasicFields&gt;
          &lt;ProductCode&gt;000011&lt;/ProductCode&gt;
          &lt;LongDescription&gt;Product A&lt;/LongDescription&gt;
      &lt;/BasicFields&gt;
  &lt;/Product&gt;
  
  &lt;Product&gt;
      &lt;BasicFields&gt;
          &lt;ProductCode&gt;000012&lt;/ProductCode&gt;
          &lt;LongDescription&gt;Product B&lt;/LongDescription&gt;
      &lt;/BasicFields&gt;
      &lt;Barcode&gt;         
        &lt;Eancode&gt;5391524344444&lt;/Eancode&gt;        
      &lt;/Barcode&gt;
  &lt;/Product&gt;
  &lt;/ProdExtract&gt;
  </code></pre>
  
  <p>My C# code to is as follows.</p>
  
  <pre><code>foreach (XmlNode node in nodes)                        
  {
     XmlNodeList barcodeExists = xDoc.GetElementsByTagName("Product/Barcode");
  
     if (barcodeExists.Count &gt; 0)
     {
        /*get the inner text of that node*/
        p.q_barcode = node.SelectSingleNode("Barcode/Eancode").FirstChild.InnerText;
     }
     else
     {
        /* ---
        If product has no Barcode node,
        Lets set our default value for products without that node
        --- */        
     }
  }
  </code></pre>
  
  <p>Now when the check goes through the first record that does not have the barcode node, it is going to the <code>else</code> statement and running the code needed to generate a value and inserting that first record perfectly. On the second check for the record with all nodes it is still somehow jumping over to the the <code>else</code> and generating a value when it should simple take the value from the <code>if</code> inner text of the "Barcode/Eancode". Even swapping around the records and putting Product B first is still giving the same issue.</p>
  
  <p>I have even tried the following way, and its still not getting the appropriate value for Product B</p>
  
  <pre><code>var barcodeExists = node.SelectSingleNode("Product/Barcode");
  
  if (barcodeExists != null)
  {
     /*Barcode node exists, get the value from that node*/
     p.q_barcode = node.SelectSingleNode("Barcode/Eancode").FirstChild.InnerText;
  }
  </code></pre>