C#XML读写 [英] C# XML Read And Write

查看:65
本文介绍了C#XML读写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Customers
    {
        public int CustId { get; set; }
        public string Name { get; set; }
        public long MobileNo { get; set; }
        public string Location { get; set; }
        public string Address { get; set; }

        StringWriter stringWriter = new StringWriter();



        // UserInput
        public void InsertCustomer()
        {
            Console.WriteLine("Enter Your Id");
            CustId = int.Parse(Console.ReadLine());

            Console.WriteLine("Enter Your Name");
            Name = Console.ReadLine();

            Console.WriteLine("Enter Your Mobile No");
            MobileNo = long.Parse(Console.ReadLine());

            Console.WriteLine("Enter Your Location");
            Location = Console.ReadLine();

            Console.WriteLine("Enter Your Address");
            Address = Console.ReadLine();

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(@"CustomersDetail.xml");

                if (doc.ChildNodes.Count == 0)
                {
                    // It is empty 
                    XDocument xDoc = 
                        new XDocument(    
                            new XDeclaration("1.0", "utf-8", "yes"),  
                            new XComment("LINQ To XML Demo"),       
                            new XElement("Customers",           
                            new XElement("Customer",           
                            new XElement("CustId", CustId),     
                            new XElement("Name", Name),         
                            new XElement("MobileNo", MobileNo),  
                            new XElement("Location", Location),   
                            new XElement("Address", Address))));


                    xDoc.Save(stringWriter);
                    xDoc.Save(@"CustomersDetail.xml");
                    Console.WriteLine("\n Created new XML \n" + stringWriter);
                }
                else if (doc.ChildNodes.Count > 1)
                {

                    //if (xDoc.ChildNodes.Count > 1)
                    // There are more children on the **root level** of the DOM
                    XDocument xdoc = XDocument.Load(@"CustomersDetail.xml");

                    xdoc.Element("Customers").Add(
                        new XElement("Customer",
                            new XElement("CustId", CustId),
                            new XElement("Name", Name),
                            new XElement("MobileNo", MobileNo),
                            new XElement("Location", Location),
                            new XElement("Address", Address)));

                    xdoc.Save(stringWriter);
                    xdoc.Save(@"CustomersDetail.xml");
                    Console.WriteLine("\n Added \n" + stringWriter);
                }
            }
            catch(XmlException exc)
            {
                //invalid file
                Console.WriteLine("Sorry");

            }

        }
        
    }










class Program
    {
        static void Main(string[] args)
        {
            Customers myCustomers = new Customers();  
            myCustomers.InsertCustomer();   
            Console.ReadLine();
            
        }
    }





运行此程序



用户输入工作

然后显示

例外

对不起



我的逻辑是创建XML文件命名为CustomersDetail.xml

构建其显示调试文件夹时



用户输入<如果XML为空,则为






run this program

user input working
then its showing
exception
Sorry

My logic is create XML file Named in "CustomersDetail.xml"
when build its showing debug folder

user input
if XML is empty

XDocument xDoc = 
                        new XDocument(    
                            new XDeclaration("1.0", "utf-8", "yes"),  
                            new XComment("LINQ To XML Demo"),       
                            new XElement("Customers",           
                            new XElement("Customer",           
                            new XElement("CustId", CustId),     
                            new XElement("Name", Name),         
                            new XElement("MobileNo", MobileNo),  
                            new XElement("Location", Location),   
                            new XElement("Address", Address))));
 

                    xDoc.Save(stringWriter);
                    xDoc.Save(@"CustomersDetail.xml");
                    Console.WriteLine("\n Created new XML \n" + stringWriter);







else

添加其他详细信息CustomersDetail.xml

不会丢失以前的数据






else
Add another details same CustomersDetail.xml
don't loose previous data

XDocument xdoc = XDocument.Load(@"CustomersDetail.xml");
 
                    xdoc.Element("Customers").Add(
                        new XElement("Customer",
                            new XElement("CustId", CustId),
                            new XElement("Name", Name),
                            new XElement("MobileNo", MobileNo),
                            new XElement("Location", Location),
                            new XElement("Address", Address)));
 
                    xdoc.Save(stringWriter);
                    xdoc.Save(@"CustomersDetail.xml");
                    Console.WriteLine("\n Added \n" + stringWriter);










Quote:

XML文档中没有保存



i想要输入的内容保存在XML文件中

nothing saved inside the XML document

i want to what i am input save inside the XML File

推荐答案

这里的问题是你要覆盖XML文件,丢失数据;解决方法是在根据用户输入附加第一个记录/元素之前创建一个正确的初始 XML文档,然后重新使用该XMLDocument将新元素附加到。我建议:



I.a.存储用作Program类的静态成员的完整文件路径。然后,您可以通过Program.file路径在'Customer Class>中访问它。


1.b.确保在程序的主要方法中有一个有效的XML模板:
The problem here is that you are overwriting the XML file, and losing data; the solution for that is creating a proper initial XML document prior to appending the first record/Element based on user input, and, then, re-using that XMLDocument to append new Elements to. I suggest:

I.a. store the full filepath used as a static member of the Program class. You can then access it in the 'Customer Class via Program.filepath

1.b. make sure you have a valid "template" for XML in the Program 'Main method:
class Program
{
    public static string filepath = @"C:\Users\YourUserName\Desktop\CustomerData\CustomersDetail.xml";

    public static XDocument xDoc;

    static void Main(string[] args)
    {
        if (!File.Exists(filepath))
        {
            // create a template for adding Elements to in code
            Program.xDoc =
                new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XComment("LINQ To XML Demo"),
                    new XElement("Customers"));
            Program.xDoc.Save(filepath);
        }
        else
        {
            // load the existing XML document
            xDoc = XDocument.Load(filepath);
        }

        // now instantiate your Customer Class
        // and call InsertCustomer, etc.
    }
}

II。在Customer Class中,您只需要将附加 Customer对象的实例处理到现有XML文件:

II. In the Customer Class, you should then only have to handle appending instances of the Customer object to the exiting XML file:

// in 'InsertCustomer method after all reads are done:
try
{
    // defensive programming !
    if(Program.xDoc == null) Program.xDoc = XDocument.Load(Program.filepath);
    
    // create the new element using existing code and Program.xDoc

    // append the new element, save result, etc. using existing code and Program.xDoc
}
catch (XmlException exc)
{
    // append problem
    Console.WriteLine("append problem: {0}", exc.Message);
}

这里的另一个策略是将有效的文件路径和有效的XMLDocument引用作为参数传递给'Customers类的构造函数。我保证这会有效,因为我在过去几次写过这样的代码。

Another strategy here would be to pass the valid file-path and valid XMLDocument reference as parameters to the constructor of the 'Customers Class. I guarantee this will work because I've written code like this in the past several times.


这篇关于C#XML读写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆