title: C# Linq to XML add, update, delete
body: <p>I have this code</p>
  
  <pre><code>        XElement newClient= new XElement("Client",
              new XElement("Name", cmbClient.Text),
              new XElement("Service",
                  new XElement("ServName", cmbService.Text)));
          xmlDoc.Add(newClient);
          xmlDoc.Save("Settings.xml");
  </code></pre>
  
  <p>Which creates this</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;Clients&gt;
    &lt;Client&gt;
      &lt;Name&gt;Client Name&lt;/Name&gt;
      &lt;Services&gt;
        &lt;ServName&gt;Service Name&lt;/ServName&gt;
      &lt;/Services&gt;
    &lt;/Client&gt;
  &lt;/Clients&gt;
  </code></pre>
  
  <p>If i press again Button1, then It will create another Client section, that's OK but what I want is:</p>
  
  <ol>
  <li>Create a new Client section if it does <strong>not</strong> exists. </li>
  <li>If Client exists, then <strong>add</strong> a ServName to it, instead of replacing
  what already has.</li>
  <li>If a service already exists on a client, then do nothing, because already exists.</li>
  </ol>
  
  <p>Any clue? I'm starting with linq to xml... thanks in advice!</p>
  
  <p>EDIT: Solution provided by mixin answers from Dmitry Dovgopoly and Leon Newswanger thank you two! :D</p>
  
  <pre><code>XDocument xDoc = XDocument.Load("Settings.xml");
  var Clients =
      from client in xDoc.Root.Elements("Client")
      where client.Element("Name").Value == cmbClient.Text
      select client;
  if (Clients.Count() &gt; 0)
  {
      var Client =
          (from client in xDoc.Root.Elements("Client")
          where client.Element("Name").Value == cmbClient.Text
          select client).Single();
              if (Client.Element("Services").Elements().Count(el =&gt; el.Value == cmbService.Text) == 0)
              {
                  Client.Element("Services").Add(new XElement("ServName", cmbService.Text));
              }
  }
  else
  {
      XElement newClient = new XElement("Client",
          new XElement("Name", cmbClient.Text),
          new XElement("Services",
              new XElement("ServName", cmbService.Text)));
      xDoc.Root.Add(newClient);
  }
  xDoc.Save("Settings.xml");
  </code></pre>