2012-01-16 52 views
1

我有兩個文本框,分別是txtUserid和txtPassowrd。我正在將文本框中輸入的值寫入xmlfile,但我不希望相同的txtuserid值在xml中寫入兩次 - 它應該被覆蓋;即如果我輸入txtUserid = 2和txtPassword = I,第二次如果我輸入txtUserid = 2和txtPassword = m,那麼我只想在xml中輸入一個條目...即txtUserid = 2和textPassword = m將文本框值寫入C#中的xml文件.net

是我的代碼

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

不要以純文本形式將密碼保存在xml文件中。 – 2012-01-16 16:04:53

+0

目前我不能做代碼細節,但最簡單的方法是在創建新代碼之前刪除任何現有的用戶節點。 – 2012-01-16 16:06:14

回答

0

搜索現有的XML文檔,其中用戶ID屬性匹配當前的一個,如果確實如此,修改一個節點,否則做一個新的。

我想像你的折軸將類似於以下:

 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); 
+0

如何編寫用於修改現有節點的代碼??我對C#新增了一個# – user451387 2012-01-16 16:41:30

+0

我們是否需要爲此文章添加「作業」標記? – 2012-01-16 17:12:40

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(); 
}