如何在C#中更新XML文件?

时间:2015-11-09 02:09:32

标签: c# xml

我拥有的XML文件:

<NameList>
  <personDetail>
    <first_name>Rock</first_name>
    <last_name>Shajahan</last_name>
    <age>24</age>
  </personDetail>
</NameList>

主要:

             XDocument doc = XDocument.Load(@"nameList.xml");

         var node = doc.Descendants("personDetail").FirstOrDefault(personDetail => personDetail.Element("first_name").Value == this.textBox1.Text);


         node.SetElementValue("first_name", this.textBox1.Text);
         node.SetElementValue("last_name", this.textBox2.Text);
         node.SetElementValue("age", this.textBox3.Text);

        Console.WriteLine(node);
        doc.Save(@"nameList.xml");

当我通过 node.SetElementValue(&#34; age&#34;,this.textBox3.Text)更新以更改其他变量时,我没有红色ID变量(例如last_name)一切正常。但如果我想改变&#34; root&#34; &#34; first_name&#34;,它将显示&#34;未处理的类型&#39; System.NullReferenceException&#39;发生&#34;

1 个答案:

答案 0 :(得分:1)

//试试这段代码

        string path = "path";
        var element = "first_name";
        var value = "Dev";

        try
        {
            string fileLoc = path;
            XmlDocument doc = new XmlDocument();
            doc.Load(fileLoc);
            XmlNode node = doc.SelectSingleNode("/NameList/personDetail/" + element);
            if (node != null)
            {
                node.InnerText = value;
            }
            else
            {
                XmlNode root = doc.DocumentElement;
                XmlElement elem;
                elem = doc.CreateElement(element);
                elem.InnerText = value;
                root.AppendChild(elem);
            }
            doc.Save(fileLoc);
            doc = null;
        }
        catch (Exception)
        {

        }