简体   繁体   English

如何创建,读取和编写XML C#Windows窗体?

[英]How to create, read and write XML C# windows forms?

I want to create an XML file through c# and need to read and write on it. 我想通过c#创建一个XML文件,并且需要对其进行读写。

The data I need to store are just strings and integers. 我需要存储的数据只是字符串和整数。

Roughly three options (I shall assume at least .NET 3.5): 大约三个选项(我至少应假设.NET 3.5):

  1. Settings as per @Andrew 按照@Andrew的设置
  2. The built in Serialization tools which work a treat and do some of the heavy lifting for you. 内置的序列化工具可以为您服务,并为您带来一些繁重的工作。
  3. Use Linq to XML (XDocument, XElement, XAttribute etc) which makes it relatively trivial to manually read and write XML in whatever format you require . 使用Linq转换XML(XDocument,XElement,XAttribute等),这使得手动读取和写入所需格式的XML相对简单。

To be honest you'll probably achieve the result you want fastest using Linq to XML and its also probably the most flexible approach however you ought to consider what is the most appropriate solution for your particular application - eg if the values you're saving are application settings then using the configuration/settings may be more appropriate. 老实说,使用Linq to XML及其可能也是最灵活的方法,您可能会最快获得所需的结果,但是您应该考虑哪种方法最适合您的特定应用程序-例如,如果要保存的值然后使用配置/设置进行应用程序设置可能更合适。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Xml;
    using System.Data;

    namespace DomenNotification
    {
        class CreateXML
        {
            public static string Title = "";
            public static string Hosting = "";
            public static string Startdate = "";
            public static string ExpDate = "";
            public static string Username = "";
            public static string Password = "";

            public string Title1 { get; set; }
            public string Hosting1 { get; set; }
            public string Startdate1 { get; set; }
            public string ExpDate1 { get; set; }
            public string Username1 { get; set; }
            public string Password1 { get; set; }


            public string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Notification.xml"; // This is the path of MyDocuments folder of your pc

           //---------------create xml file -----------------------

            public bool isXmlExist(string filePath)
            {
                bool result = false;
                try
                {
                    if (File.Exists(filePath))// Checking the file if exist
                    {
                        Startdate = DateTime.Now.ToShortDateString();
                        result = true;
                    }
                    else
                    {
                        XmlDocument doc = new XmlDocument();
                        XmlElement element1 = doc.CreateElement("", "XML", "");
                        doc.AppendChild(element1);

                        //--------------creating the node elements

                        XmlElement element2 = doc.CreateElement("", "Title", "");
                        element1.AppendChild(element2);

                        XmlElement element3 = doc.CreateElement("", "Hosting", "");
                        element1.AppendChild(element3);

                        XmlElement element4 = doc.CreateElement("", "StartDate", "");
                        element1.AppendChild(element4);

                        XmlElement element5 = doc.CreateElement("", "ExpDate", "");
                        element1.AppendChild(element5);

                        XmlElement element6 = doc.CreateElement("", "Username", "");
                        element1.AppendChild(element6);

                        XmlElement element7 = doc.CreateElement("", "password", "");
                        element1.AppendChild(element7);

                        doc.Save(filePath);
                        Startdate = DateTime.Now.ToShortDateString();
                        //writeXml(filePath);

                        result = true;
                    }
                }
                catch { result = false; }
                return result;
            }

                //-------------------Getting the xml data from creating file ---                 
            public DataSet getXmlData(string filePath)
            {
                DataSet ds = new DataSet();
                try
                {
                    if (isXmlExist(filePath))
                    {
                        ds.Clear();
                        ds.ReadXml(filePath);
                        int table = Convert.ToInt32(ds.Tables.Count);
                        for (int i = 0; i <= table; i++)
                        {
                            Title = ds.Tables[i].Rows[0][0].ToString();
                            Hosting = ds.Tables[i].Rows[0][1].ToString();
                            Startdate = ds.Tables[i].Rows[0][2].ToString();
                            ExpDate = ds.Tables[i].Rows[0][3].ToString();
                            Username = ds.Tables[i].Rows[0][4].ToString();
                            Password = ds.Tables[i].Rows[0][5].ToString();
                        }
                        return ds;
                    }
                    return ds;
                }
                catch { return ds; }
            }

//------------------- insert the data into created xml file--------------

            public bool writeXml(string filePath,string title,string hosting,string sdate,string exdate,string username,string password)
            {
                bool result = false;
                Title = title;
                Hosting = hosting;
                Startdate = sdate;
                ExpDate = exdate;
                Username = username;
                Password = password;
                DataSet ds = new DataSet();
                DataTable dt = new DataTable();
                ds.Clear();
                ds.ReadXml(path);
                int i = 0;
                i = Convert.ToInt32(ds.Tables[0].Rows.Count) - 1;
                try
                {

                    dt.Columns.Add("Title");
                    dt.Columns.Add("Hosting");
                    dt.Columns.Add("StartDate");
                    dt.Columns.Add("ExpDate");
                    dt.Columns.Add("Username");
                    dt.Columns.Add("Password");


                    dt.Rows.Add(dt.NewRow());
                    dt.Rows[i]["Title"] = Title;
                    dt.Rows[i]["Hosting"] = Hosting;
                    dt.Rows[i]["Startdate"] = Startdate;
                    dt.Rows[i]["ExpDate"] = ExpDate;
                    dt.Rows[i]["Username"] = Username;
                    dt.Rows[i]["Password"] = Password;

                    ds.Tables.Add(dt);

                    ds.WriteXml(path);
                    result = true;
                }
                catch { }
                return result;
            }

        }
    }

Please see Using Settings in C# : 请参阅在C#中使用设置

The .NET Framework 2.0 allows you to create and access values that are persisted between application execution sessions. .NET Framework 2.0允许您创建和访问在应用程序执行会话之间保留的值。 These values are called settings. 这些值称为设置。 Settings can represent user preferences, or valuable information the application needs to use. 设置可以代表用户首选项或应用程序需要使用的有价值的信息。 For example, you might create a series of settings that store user preferences for the color scheme of an application. 例如,您可以创建一系列设置来存储用户对应用程序配色方案的首选项。 Or you might store the connection string that specifies a database that your application uses. 或者,您可以存储指定应用程序使用的数据库的连接字符串。 Settings allow you to both persist information that is critical to the application outside of the code, and to create profiles that store the preferences of individual users. 设置使您不仅可以在代码之外保留对应用程序至关重要的信息,还可以创建存储个人用户首选项的配置文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM