-1

有人可以检查我的代码,看看我做错了什么我正在尝试向 XML 文件添加一个条目。它几乎可以工作了,当我添加条目名称年龄和电子邮件时,它们正在被填充,除非我检查文件而不是说 bill bill@zzz.com 28 它只显示账单账单。据我所见,一切看起来都很好,并且关闭得很好,但我想征求别人的意见。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.IO;


public partial class compnew : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        XDocument doc = XDocument.Load(Server.MapPath("~/comp.xml"));
        var comp = from itm in doc.Descendants("people") select itm;
        StreamWriter stream = new StreamWriter(Server.MapPath("~/comp.xml"));
        stream.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
        stream.WriteLine("<comp>");

        stream.WriteLine("<people>");
        stream.WriteLine("<name>" + txtName.Text + "</name>");
        stream.WriteLine("<email>" + txtName.Text + "</email>");
        stream.WriteLine("<age>" + txtName.Text + "</age>");
        stream.WriteLine("</people>");

        foreach (var item in comp){
            stream.WriteLine("<people>");
            stream.WriteLine("<name>" + item.Descendants("name").First().Value.ToString() + "</name>");
            stream.WriteLine("<email>" + item.Descendants("email").First().Value.ToString() + "</email>");
            stream.WriteLine("<age>" + item.Descendants("age").First().Value.ToString() + "</age>");
            stream.WriteLine("</people>");
        }

        stream.WriteLine("</comp>");
        stream.Close();

        txtName.Text = "";
        txtEmail.Text = "";
        txtAge.Text = "";
        DataList1.DataBind();
        Response.Write("Thank you");
    }
}
4

2 回答 2

2

从您的代码:

stream.WriteLine("<name>" + txtName.Text + "</name>");
stream.WriteLine("<email>" + txtName.Text + "</email>");
stream.WriteLine("<age>" + txtName.Text + "</age>");

您正在编写“txtName.Text”作为所有这些的值,而不是 txtEmail.Text 或任何您的字段名称。

于 2013-04-24T14:35:11.827 回答
0

您已txtName.Text被保存到<name><email><age>

    stream.WriteLine("<name>" + txtName.Text + "</name>");
    stream.WriteLine("<email>" + txtName.Text + "</email>");
    stream.WriteLine("<age>" + txtName.Text + "</age>");

也许改用txtEmailand txtAge

    stream.WriteLine("<name>" + txtName.Text + "</name>");
    stream.WriteLine("<email>" + txtEmail.Text + "</email>");
    stream.WriteLine("<age>" + txtAge.Text + "</age>");
于 2013-04-24T14:37:14.387 回答