将文本框值写入C#.net中的xml文件

时间:2012-01-16 16:01:28

标签: c# xml

我有两个文本框,即txtUserid和txtPassowrd。我正在将文本框中输入的值写入xmlfile,但我不希望在xml中将相同的txtuserid值写入两次 - 它应该被覆盖;即如果我输入txtUserid = 2和txtPassword = I,第二次输入txtUserid = 2和txtPassword = m,那么我只需要xml中的一个条目...即txtUserid = 2和textPassword = m

这是我的代码

XDocument Xdoc = new XDocument(new XElement("Users"));
if (System.IO.File.Exists("D:\\Users.xml"))
    Xdoc = XDocument.Load("D:\\Users.xml");
else
    Xdoc = new XDocument();

XElement xml = new XElement("Users",
               new XElement("User",
               new XAttribute("UserId", txtUserName.Text),
               new XAttribute("Password", txtPassword.Text)
               ));

if (Xdoc.Descendants().Count() > 0)
    Xdoc.Descendants().First().Add(xml);
else
{
    Xdoc.Add(xml);
}

Xdoc.Save("D:\\Users.xml");

2 个答案:

答案 0 :(得分:0)

在现有XML文档中搜索UserId属性与当前属性匹配的节点,如果匹配,则修改该属性,否则重新创建新文件。

我想你的coude会像下面那样:

        List<XElement> list = Xdoc.Descendants("User").Where(el => el.Attribute("UserId").Value == txtUserName.Text).ToList();
        if (list.Count == 0)
        {
            // Add new node
        }
        else
        {
            // Modify the existing node
        }

编辑:为了回应您的评论,编辑您的XElement的代码看起来像

string myValue = "myValue";
list.First().Attribute("ElementName").SetValue(myValue);

答案 1 :(得分:0)

将文本框值写入C#

中的XML文件
protected void btnSave_Click(object sender, EventArgs e)
{   
    // Open the XML doc  
    System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
    myXmlDocument.Load(Server.MapPath("InsertData.xml"));
    System.Xml.XmlNode myXmlNode = myXmlDocument.DocumentElement.FirstChild;

    // Create new XML element and populate its attributes  
    System.Xml.XmlElement myXmlElement = myXmlDocument.CreateElement("entry");
    myXmlElement.SetAttribute("Userid", Server.HtmlEncode(textUserid.Text));
    myXmlElement.SetAttribute("Username", Server.HtmlEncode(textUsername.Text));
    myXmlElement.SetAttribute("AccountNo", Server.HtmlEncode(txtAccountNo.Text));
    myXmlElement.SetAttribute("BillAmount", Server.HtmlEncode(txtBillAmount.Text));


    // Insert data into the XML doc and save  
    myXmlDocument.DocumentElement.InsertBefore(myXmlElement, myXmlNode);
    myXmlDocument.Save(Server.MapPath("InsertData.xml"));

    // Re-bind data since the doc has been added to  
    BindData();


    Response.Write(@"<script language='javascript'>alert('Record inserted Successfully Inside the XML File....')</script>");
    textUserid.Text = "";
    textUsername.Text = "";
    txtAccountNo.Text = "";
    txtBillAmount.Text = "";  
}

void BindData()
{
    XmlTextReader myXmlReader = new XmlTextReader(Server.MapPath("InsertData.xml"));
    myXmlReader.Close();
}