【问题标题】:how to write data to XML file in asp.net c#?如何在 asp.net c# 中将数据写入 XML 文件?
【发布时间】:2019-06-25 10:56:39
【问题描述】:

我正在尝试将用户输入数据写入 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);
}

没有错误显示 不存储值。

【问题讨论】:

标签: c# asp.net xml


【解决方案1】:

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

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

2 个错误原因。

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

基本的xml结构:

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

</Contacts>

【讨论】:

    猜你喜欢
    • 2014-03-20
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 2016-06-07
    • 1970-01-01
    • 2010-10-26
    相关资源
    最近更新 更多