title: Create dynamic xml using xelement in c#
body: <p>I want to create xml using <code>XElement</code> as you can see:</p>
  
  <pre><code>XDocument RejectedXmlList = new XDocument
  (
      new XDeclaration("1.0", "utf-8", null)
  );
  int RejectCounter = 0;
  
  foreach (Parameter Myparameter in Parameters)
  {
      if (true)
      {
          XElement xelement = new XElement(Myparameter.ParameterName, CurrentData.ToString());
          RejectedXmlList.Add(xelement);
      }
  }
  </code></pre>
  
  <p>As you can see if the condition is OK the parameter should be added to <code>RejectedXmlList</code> but instead I get this exception:</p>
  
  <pre class="lang-none prettyprint-override"><code>This operation would create an incorrectly structured document.
  </code></pre>
  
  <p>Of note, the first parameter is added successfully.  Only when the second one is added do I get the exception.</p>
  
  <p>The expected result should be like this:</p>
  
  <pre><code>&lt;co&gt;2&lt;/co&gt;
  &lt;o2&gt;2&lt;/o2&gt;
  ....
  </code></pre>