写入xml文件,但不包含所有结果

本文关键字:包含所 结果 xml 文件 写入 | 更新日期: 2023-09-27 18:10:54

有人可以检查我的代码,看看我做错了什么,我试图添加一个条目到XML文件。它几乎工作,当我添加条目名称年龄和电子邮件,他们正在填充,除了当我检查文件,而不是说账单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");
    }
}

写入xml文件,但不包含所有结果

从你的代码:

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

你写的是"txtName"。Text"作为它们的值,而不是txtEmail。文本或者其他字段名

txtName.Text保存为<name>, <email><age>

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

可以改成txtEmailtxtAge

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