title: How does one increment/update integer value of an XML Attribute in C# (XAttribute)?
body: <p><strong>TL;DR</strong>: If I have an <code>XAttribute</code> of <code>NumFruits</code> in an <code>XElement</code>, how can I increment/update the value from 0 to 1,2,3... ? </p>
  
  <p><strong>The issue:</strong> </p>
  
  <p>When I attempt to increment the XAttribute like so:</p>
  
  <pre><code>basket.Attribute("numFruits").Value += 1 
  </code></pre>
  
  <p>the result for <code>numFruits</code> will be <code>numFruits = 01</code> (since 0 was the initial value), when the intended result was supposed to be <code>numFruits = 1</code></p>
  
  <p>Global variables that are added at the end of the parsing is not desired as there can be many baskets.</p>
  
  <p><strong>Explanation:</strong></p>
  
  <p>In C# Linq to XML, one can add <code>XAttributes</code> to an <code>XElement</code> like so. </p>
  
  <p><code>XElement basket = new XElement("Marys_Basket", new XAttribute("NumFruits", 0);</code></p>
  
  <p>where in the example we use <code>NumFruits</code> <code>XAttribute</code> as a counter to keep track of number of fruits in the <code>XDocument</code>. </p>
  
  <p>As I interate through a list of (for example) Fruit objects that each also have a <code>basket_owner</code> property, I serialize all those objects to XML manually by creating or adding to <code>XElements</code> which in this example would be the owners.</p>
  
  <p>As the list of fruits is not fixed, I have to add Fruit elements to the XElement and update the <code>XAttribute</code> by first checking if the owner element exists (I've done this with LINQ queries and checking if they are null) and then adding the Fruit XElement as a child, yielding something like so:</p>
  
  <pre><code>&lt;Root&gt;
    &lt;Marys_basket numFruits=2&gt;
       &lt;Fruit name="Mango"/&gt;
       &lt;Fruit name="Papaya"/&gt;
    &lt;/Marys_basket&gt;
    &lt;Jons_basket numFruits=0 /&gt;
    &lt;Bobs_basket numFruits=1&gt; 
       &lt;Fruit name="Apple"/&gt;
    &lt;/Bobs_basket&gt;
  &lt;/Root&gt;
  </code></pre>
  
  <p>Here's a <a href="https://stackoverflow.com/questions/17821750/increment-a-xml-with-c-sharp">related question</a> on how to increment an XML Element (in this case XElement), but not an XAttribute. And <a href="https://stackoverflow.com/questions/6053577/update-xattribute-value-where-xattribute-name-x">this as well</a> but not specifically to increasing a value.</p>
  
  <p>I've found one method (posted as an answer) and would like to explore a more robust way to do so. As my program does this multiple times.</p>