2012-01-16 12 views
1

私は2つのテキストボックスtxtUseridとtxtPassowrdを持っています。テキストボックスに入力された値をxmlfileに書き込んでいますが、同じtxtuserid値をxmlに2回書き込む必要はありません。上書きする必要があります。つまり、txtUserid = 2とtxtPassword = Iを入力し、txtUserid = 2とtxtPassword = mと入力するとxmlに1つのエントリしか入れません。つまり、txtUserid = 2とtextPassword = mC#.netのxmlファイルにテキストボックス値を書き込む

ここに私のコード

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ファイルにプレーンテキストで保存しないでください。 –

+0

現時点ではコードの詳細を記述することはできませんが、最も簡単な方法は、新しいユーザーノードを作成する前に既存のユーザーノードを削除することです。 –

答えて

0

は他に、ユーザーID属性は、現在のものと一致し、それがない場合には、その内1つを変更するノードに対して、既存のXMLドキュメントを検索し、新しいものを作るです。

私はあなたの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); 
+0

既存のノードを変更するためのコードを書く方法?私はC#を初めて使用しました – user451387

+0

この記事に「宿題」タグを追加する必要はありますか? –

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(); 
} 
関連する問題