c#,请问如何把testbox的内容写入xml文件,然后从combobox中显示出来??

2024-12-19 00:02:42
推荐回答(2个)
回答1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace Form
{
    public partial class Form4 : Form
    {
        public Form4()
        {
            InitializeComponent();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            this.button1_Click(null, null);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string data = this.textBox1.Text.Trim();

            string fileName = Path.Combine(Application.StartupPath, "data.xml");
            XmlDocument doc = new XmlDocument();
            //加载Xml数据
            try
            {
                doc.Load(fileName);
            }
            catch (Exception ex)
            {
                doc = this.ReCreateXmlFile(fileName);
            }
            if (!doc.HasChildNodes)
            {
                MessageBox.Show("Xml文件加载发生错误!");
                return;
            }

            XmlNode rootNode = doc.GetElementsByTagName("ROOT")[0];
            //将新数据加入Xml中
            if (!string.IsNullOrEmpty(data))
            {
                //新建节点
                XmlNode childNode = doc.CreateNode(XmlNodeType.Element, "DATA", "");
                childNode.InnerText = data;
                rootNode.AppendChild(childNode);
                //保存到文件
                doc.Save(fileName);
            }

            this.comboBox1.Items.Clear();
            //将Xml节点数据加载到ComboBox
            foreach (XmlNode child in rootNode.ChildNodes)
            {
                this.comboBox1.Items.Add(child.InnerText);
            }
        }

        /// 
        /// 新创建文件
        /// 

        /// 
        private XmlDocument ReCreateXmlFile(string fileName)
        {
            if (File.Exists(fileName)) File.Delete(fileName);

            using (FileStream fs = File.Create(fileName))
            {
                XmlDocument doc = new XmlDocument();
                XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", "");
                doc.AppendChild(decl);
                XmlElement rootNode = doc.CreateElement("ROOT");
                doc.AppendChild(rootNode);
                doc.Save(fs);

                return doc;
            }
        }
    }
}

回答2:

那你百度 c# xml操作 吧