如何在XML文件中插入数据 [英] how to insert data ino xml file

查看:98
本文介绍了如何在XML文件中插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个代码..

i write a code..

protected void Button1_Click(object sender, EventArgs e)
    {
        XmlDocument myxmldocument = new XmlDocument();
        myxmldocument.Load(Server.MapPath("Register.xml"));
        XmlNode myxmlnode = myxmldocument.DocumentElement.FirstChild;

        XmlElement myXmlElement = myxmldocument.CreateElement("Name", Server.HtmlEncode(TextBox1.Text));
       
        myXmlElement.SetAttribute("Name", Server.HtmlEncode(TextBox1.Text));
        myXmlElement.SetAttribute("Password", Server.HtmlEncode(TextBox2.Text));
        myXmlElement.SetAttribute("Email", Server.HtmlEncode(TextBox3.Text));
        myXmlElement.SetAttribute("Gender", Server.HtmlEncode(DropDownList1.SelectedItem.Text));
        myXmlElement.SetAttribute("Location", Server.HtmlEncode(TextBox4.Text));
        myXmlElement.SetAttribute("DateofBirth", Server.HtmlEncode(TextBox5.Text));

        myxmldocument.DocumentElement.InsertBefore(myXmlElement, myxmlnode);
        myxmldocument.Save(Server.MapPath("Register.xml")); 

         BindData(); 
         lblmsg.Text = "Record Entered Successfully Inside XML File..."; 
         TextBox1.Text="";
         TextBox2.Text="";
         TextBox3.Text="";
         TextBox4.Text="";
         TextBox5.Text="";
    } 

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


像这样的数据患者


the data patients like this

<employee name="Ravi" password="ravi" email="ravi@gmail.com" gender="Male" location="Hyderabad" dateofbirth="26/06/1989" xmlns="Ravi">



但我想要xml的实际格式



but i want actual format of xml

<employee>
<name>Ravi
<password>ravi
.
.
.
.
.


这样您可以帮我吗


like this can u help me

推荐答案

假设您的根元素employee存在于XML文件中,那么您的代码就会出现问题,因为myxmlnode将如果您的根节点目前没有子元素,则始终指向null.您可能可以像这样编辑分配值的方式.
Assuming your root element employee exists on the XML file, there would be a problem on your code, since myxmlnode will always point to null if your root node does not have child elements at the moment. You can probably edit the way you assign the value like this.
XmlNode myxmlnode = myxmldocument.DocumentElement;


然后,您可以像这样将子节点添加到您的根节点(员工).


And then, you can then add child nodes to your root node(employee) like this.

XmlElement myXmlElement = myxmldocument.CreateElement("Name");
myXmlElement.InnerText = Server.HtmlEncode(TextBox1.Text);
myxmlnode.AppendChild(myXmlElement);


这是否正常工作,我添加了像这样的子对象

Is this working correctly i add childs like this

XmlText text = myxmldocument.CreateTextNode(Server.HtmlEncode(TextBox1.Text)); myxmldocument.DocumentElement.AppendChild(myXmlElement);
myxmldocument.DocumentElement.LastChild.AppendChild(text);



但是o/p显示正确的格式.....



But o/p shows correct format.....


这篇关于如何在XML文件中插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆