如何在ASP.NET C#中将数据写入XML文件?

时间:2019-06-25 10:56:39

标签: c# asp.net xml

我正在尝试将用户输入数据写入asp.net/C#中的XML文件。 数据将在文本框中输入。

C#代码:

int i = 0;
protected void submit(object sender,EventArgs e)
{
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(Server.MapPath("~/XMLFile1.xml"));
    Console.WriteLine(xdoc);
    XmlElement contact = xdoc.CreateElement("Contact");

    XmlAttribute Count = xdoc.CreateAttribute("Count");
    i = i + 1;
    Count.Value = i.ToString();

    XmlElement Name = xdoc.CreateElement("Name");
    XmlText xmlName = xdoc.CreateTextNode(name.Text);

    XmlElement EmailId = xdoc.CreateElement("EmailId");
    XmlText xmlemail = xdoc.CreateTextNode(emailId.Text);

    XmlElement Comments = xdoc.CreateElement("Comments");
    XmlText xmlcomment = xdoc.CreateTextNode(comments.Text);

    Name.AppendChild(xmlName);
    EmailId.AppendChild(xmlemail);
    Comments.AppendChild(xmlcomment);

    contact.Attributes.Append(Count);
    contact.AppendChild(Name);
    contact.AppendChild(EmailId);
    contact.AppendChild(Comments);

    xdoc.DocumentElement.AppendChild(contact);

    xdoc.Save(Server.MapPath("~/XMLFile1.xml"));

    Response.Redirect(Request.Url.AbsoluteUri);
}

没有错误显示 不存储值。

1 个答案:

答案 0 :(得分:0)

希望在下面的代码中抛出运行时错误。

xdoc.Load(Server.MapPath("~/XMLFile1.xml"));

2个错误原因。

  1. XMLFile1.xml在根目录中不可用。
  2. xml文件中没有基本的xml结构。

基本xml结构:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>

</Contacts>