title: C# Foreach XML Node
body: <p>I'm saving 2-dimensional coordinates on an XML file with a structure similar to:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; 
  &lt;grid&gt;
  &lt;coordinate time="78"&gt;
  &lt;initial&gt;540:672&lt;/initial&gt; 
  &lt;final&gt;540:672&lt;/final&gt; 
  &lt;/coordinate&gt;
  &lt;/grid&gt;
  </code></pre>
  
  <p>I can open the XML file and read it via the XmlTextReader, but how do I loop through the coordinates specifically to retrieve both the time attribute and data between the initial and final nodes in some format similar to:</p>
  
  <pre><code>string initial = "540:672";
  string final  = "540:672";
  int time = 78;
  </code></pre>
  
  <hr>
  
  <h2>New Code:</h2>
  
  <p>My New Code:</p>
  
  <pre><code>//Read the XML file.
  XDocument xmlDoc = XDocument.Load("C:\\test.xml");
  
  foreach (var coordinate in xmlDoc.Descendants("coordinate"))
  {
      this.coordinates[this.counter][0] = coordinate.Attribute("time").Value;
      this.coordinates[this.counter][1] = coordinate.Element("initial").Value;
      this.coordinates[this.counter][2] = coordinate.Element("final").Value;
      this.counter++;
  };
  </code></pre>
  
  <p>but now I get this error:<br>
  "Object reference not set to an instance of an object."</p>
  
  <hr>
  
  <p>XML</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;grid&gt;
    &lt;coordinate time="62"&gt;
      &lt;initial&gt;540:672&lt;/initial&gt;
      &lt;final&gt;540:672&lt;/final&gt;
    &lt;/coordinate&gt;
  
    ...
  
    &lt;coordinate time="46"&gt;
      &lt;initial&gt;176:605&lt;/initial&gt;
      &lt;final&gt;181:617&lt;/final&gt;
    &lt;/coordinate&gt;
  &lt;/grid&gt;
  </code></pre>
  
  <p>Skipped a few coordinate tags to fit, but they all had the time attribute and initial/final subtags.</p>
  
  <hr>
  
  <p>Globals</p>
  
  <pre><code>uint counter = 0;
  
          // Coordinates to be retrieved from the XML file.
          string[][] coordinates;
  </code></pre>