我使用以下程序使用C#更新存储在xml文档中的数据。
我有两个名为username
和password
的字段。如果我尝试插入数据,它将成功添加。
我的问题是当我尝试更新已存储在xml文档中的数据时。我无法更新记录。那么如何使用C#更新XLM文档中的记录?
我有以下异常NullReferenceException
,它起源于此行:
root.ReplaceChild(newCd, oldCd);
Button1_Click
添加数据,Button2_Click
更新数据。
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");
}
}
答案 0 :(得分:1)
问题似乎是XML文档和用于选择要修改的节点的XPath表达式之间的不兼容。
基于Connection()
方法中的代码,生成的XML结构将如下所示:
<records>
<record>
<username>SomeUsername</username>
<password>SomePassword</password>
</record>
</records>
在Button2_Click
事件处理程序中,您根据/catalog/cd
属性的值选择Username
节点:
oldCd = root.SelectSingleNode("/catalog/cd[Username='" + TextBox2.Text + "']");
返回null
,因为它不反映实际的XML结构。您需要更改XPath表达式以根据其内容选择oldCd
节点:
oldCd = root.SelectSingleNode("//username[contains(., '" + TextBox2.Text + "')]");