I am using the following program to update the data which is stored in xml document using C#.
I have the two fields named username and password. If i try to insert the data, it will successfully be added.
My problem is when I try to update the data which is already stored in xml document. I am not able to update the record. So how can I update the record in XLM document using C#?
I have the following exception NullReferenceException which is originated in this line:
root.ReplaceChild(newCd, oldCd);
Button1_Click adds the data, Button2_Click updates the data.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Connection();
}
protected void Connection()
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(@"D:\vijay.net\xmlstorage\XMLFile.xml");
XmlNode xmlnod = xmldoc.SelectSingleNode("records");
XmlNode xmlrec = xmlnod.AppendChild(xmldoc.CreateNode(XmlNodeType.Element, "record", ""));
xmlrec.AppendChild(xmldoc.CreateNode(XmlNodeType.Element, "Username", "")).InnerText = TextBox1.Text;
xmlrec.AppendChild(xmldoc.CreateNode(XmlNodeType.Element, "password", "")).InnerText = TextBox2.Text;
xmldoc.Save(@"D:\vijay.net\xmlstorage\XMLFile.xml");
Response.Write("Successfully saved in xml file");
TextBox1.Text = "";
TextBox2.Text = "";
}
protected void Button2_Click(object sender, EventArgs e)
{
XmlTextReader reader = new XmlTextReader(@"D:\vijay.net\xmlstorage\XMLFile.xml");
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
XmlNode oldCd;
XmlElement root = doc.DocumentElement;
oldCd = root.SelectSingleNode("/catalog/cd[Username='" + TextBox1.Text + "']");
XmlElement newCd = doc.CreateElement("cd");
newCd.SetAttribute("Password", TextBox2.Text);
newCd.InnerXml = "<Username>" + this.TextBox1.Text + "</Username>";
root.ReplaceChild(newCd, oldCd);
doc.Save(@"D:\vijay.net\xmlstorage\XMLFile.xml");
}
}
The problem seems to be an incompatibility between the XML document and the XPath expression used to select the node to modify.
Based on the code in the
Connection()method the resulting XML structure will look something like this:In the
Button2_Clickevent handler, you’re selecting the/catalog/cdnode based on the value of itsUsernameattribute:which returns
nullbecause that doesn’t reflect the actual XML structure. You need to change the XPath expression to select theoldCdnode based on its content instead: