在C#中为现有XMLNode添加属性

时间:2014-07-02 06:35:57

标签: asp.net

我正在使用xml,我必须在xml中添加新标签。 XML下面是:

<LoginDetails>
  <Login>
    <FirstName>Abhishek</FirstName>
    <LastName>Pathak</LastName>
    <securityQuestion>What is you DOB</securityQuestion>
    <SecAnswer>31/03/1985</SecAnswer>
    <LoginId>abc</LoginId>
    <Password>1234</Password>
  </Login>

</LoginDetails>

我想添加新的标签,如:

 <Login>
    <FirstName>vivek</FirstName>
    <LastName>sharma</LastName>
    <securityQuestion>What is you DOB</securityQuestion>
    <SecAnswer>27/03/1985</SecAnswer>
    <LoginId>abcd</LoginId>
    <Password>3214</Password>
  </Login>

任何人都可以用C#给我代码。

2 个答案:

答案 0 :(得分:0)

我认为您想要为登录详细信息添加节点。以下是一些可以帮助您的链接。

http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.appendchild.aspx

http://msdn.microsoft.com/en-us/library/bb387083.aspx

答案 1 :(得分:0)

所以最后我能够自己做到这一点:

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(@"D:\abhishek\LoginDetails1.xml");

    XmlElement elmRoot = xmlDoc.DocumentElement;
    XmlElement elmNew = xmlDoc.CreateElement("Login");
    elmRoot.AppendChild(elmNew);


    elmRoot = xmlDoc.DocumentElement;
    elmNew = xmlDoc.CreateElement("FirstName");
    XmlText txtVideo = xmlDoc.CreateTextNode(txtFname.Text);
    elmRoot.LastChild.AppendChild(elmNew);
    elmRoot.LastChild.LastChild.AppendChild(txtVideo);

    elmRoot = xmlDoc.DocumentElement;
    elmNew = xmlDoc.CreateElement("LastName");
    txtVideo = xmlDoc.CreateTextNode(txtLastName.Text);
    elmRoot.LastChild.AppendChild(elmNew);
    elmRoot.LastChild.LastChild.AppendChild(txtVideo);

    elmRoot = xmlDoc.DocumentElement;
    elmNew = xmlDoc.CreateElement("securityQuestion");
    txtVideo = xmlDoc.CreateTextNode(comboBox.SelectedValue.ToString());
    elmRoot.LastChild.AppendChild(elmNew);
    elmRoot.LastChild.LastChild.AppendChild(txtVideo);

    elmRoot = xmlDoc.DocumentElement;
    elmNew = xmlDoc.CreateElement("SecAnswer");
    txtVideo = xmlDoc.CreateTextNode(txtAnswer.Text);
    elmRoot.LastChild.AppendChild(elmNew);
    elmRoot.LastChild.LastChild.AppendChild(txtVideo);
    elmRoot = xmlDoc.DocumentElement;
    elmNew = xmlDoc.CreateElement("LoginId");
    txtVideo = xmlDoc.CreateTextNode(txtLoginId.Text);
    elmRoot.LastChild.AppendChild(elmNew);
    elmRoot.LastChild.LastChild.AppendChild(txtVideo);

    elmRoot = xmlDoc.DocumentElement;
    elmNew = xmlDoc.CreateElement("Password");
    txtVideo = xmlDoc.CreateTextNode(txtPwd.Text);
    elmRoot.LastChild.AppendChild(elmNew);
    elmRoot.LastChild.LastChild.AppendChild(txtVideo);

    xmlDoc.Save(@"D:\abhishek\LoginDetails.xml");