I have this 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");
Which creates this
<?xml version="1.0" encoding="utf-8"?>
<Clients>
<Client>
<Name>Client Name</Name>
<Services>
<ServName>Service Name</ServName>
</Services>
</Client>
</Clients>
If i press again Button1, then It will create another Client section, that's OK but what I want is:
- Create a new Client section if it does not exists.
- If Client exists, then add a ServName to it, instead of replacing what already has.
- If a service already exists on a client, then do nothing, because already exists.
Any clue? I'm starting with linq to xml... thanks in advice!
EDIT: Solution provided by mixin answers from Dmitry Dovgopoly and Leon Newswanger thank you two! :D
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() > 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 => 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");