简体   繁体   中英

Add XML element if it doesn't exist

I am adding a new checkbox to my frogram and need to save it's value to the setting file. I am trying to do it with the following code:

private void CloseDisconnectedCbx_CheckedChanged(object sender, EventArgs e)
{
    XDocument doc = XDocument.Load(BotsFile);
    var savedBots = doc.Descendants("SavedBots")
        .Where(p => p.Element("BotName").Value.ToLower()
                    == SelectBotBox.SelectedItem.ToString().ToLower())
        .Elements("CloseDisconnected").FirstOrDefault();
    if (savedBots == null)
    {
        try
        {
            doc.Descendants("SavedBots")
               .Where(p => p.Element("BotName").Value.ToLower()
                           == SelectBotBox.SelectedItem.ToString().ToLower())
               .FirstOrDefault()
               .Add(new XElement("CloseDisconnected",
                    Convert.ToInt32(CloseDisconnectedCbx.Checked)));
            doc.Save(BotsFile);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

It does add the new element, however, it looks like this:

<CloseDisconnected/> VALUE

It never ends the closing of the element. Is my code wrong, or have I just forgotten something?

This code is only supposed to be triggered if the element is not found in the XML file. If it is, the change will be handeled by another button.

Check parenthesis in your code

XElement xElem = new XElement("root");
xElem.Add( new XElement("CloseDisconnected", "123") ); // generates what you expect
xElem.Add( new XElement("CloseDisconnected"), "123"); // generates what you see

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM