0

the XML file that i have:

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

In the main :

             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");

I don't have red id variable, when I update by node.SetElementValue("age", this.textBox3.Text); to change other variable (e.g. last_name) there are all works fine. But if i wanna change the "root" which "first_name", it will shows "An unhandled exception of type 'System.NullReferenceException' occurred".

HCOOLH
  • 61
  • 8
  • 1
    Can you post the code that actually throws the exception? What does "I don't have red id variable" mean? As for your NullReferenceException, please refer to this: http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – vesan Nov 09 '15 at 05:14
  • Question is the last_name and age are successful. but the warning occurred when i wanna change the first_name. – HCOOLH Nov 09 '15 at 05:22

1 Answers1

1

//try this code

        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)
        {

        }
devnath
  • 36
  • 4
  • yes,It works, but still has a problem like( JOE C, 30) (Rock, B, 30) , wanna change JOE to Steven. If the age is same, It may shows (Steven C, 30) (Steven B, 30) ... Or use the method only for the root? – HCOOLH Nov 09 '15 at 05:47
  • for query try XmlNode node = doc.SelectSingleNode("/NameList/personDetail/first_name[text()='JOE']"); and value = Steven – devnath Nov 09 '15 at 06:32