简体   繁体   中英

C# XDocument - Adding a Value to an existing xml

This is what i am using

private void dir_TextBox_TextChanged(object sender, EventArgs e)
{
        string _DIR = dir_TextBox.Text.ToString();dir
        XDocument _config = XDocument.Load(@"/ProgramData\app\appConfig.xml");
        _config.Root.Element("root").Element("node1").Add(new XElement("value", _DIR));          
        _config.Save(@"/ProgramData\app\appConfig.xml");
}

I have an xml

<root>
  <node1>
    <value></value>
  </node1>
</root>

and want to add

<root>
  <node1>
    <value>a string</value>
  </node1>
</root>

I have tried several ways to do this but keep getting an error "Additional information: Object reference not set to an instance of an object."

Any help would be appreciated. Thanks.

_config.Root has already got the "root" element. And you have to set (update) a new value ("a string") to the existing element, "value" because your xml file already has the "value" element.

private void dir_TextBox_TextChanged(object sender, EventArgs e)
{
        XDocument _config = XDocument.Load(@"/ProgramData\app\appConfig.xml");
        _config.Root.Element("node1").Element("value").Value = "a string";          
        _config.Save(@"/ProgramData\app\appConfig.xml");
}

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