次のプログラムを使用して、C#を使用してxmlドキュメントに格納されているデータを更新しています。C#を使用してXMLに格納されたデータを更新するには?
username
とpassword
の2つのフィールドがあります。データを挿入しようとすると、正常に追加されます。
私の問題は、すでに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");
}
}
あなたはXmlDataSourceコントロールを見てきました、それはあなたのためにすべての作業を行います... http://msdn.microsoft。 com/ja/us/library/system.web.ui.webcontrols.xmldatasource.aspx – Lloyd