XML读写(抛出'System.Xml.XmlException)

时间:2016-01-02 11:01:58

标签: 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");

        }

    }

}

我正在尝试创建XML Db

StringWriter stringWriter = new StringWriter();
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);

我运行此代码,但重新运行代码,它将以前的数据和新数据丢失。

然后在现有XML上添加新数据的新代码

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);

但运行此代码

XDocument xdoc = XDocument.Load(@“CustomersDetail.xml”);

System.Xml.dll中出现未处理的“System.Xml.XmlException”类型异常

其他信息:缺少根元素。

帮帮我

1 个答案:

答案 0 :(得分:0)

这里有一些问题:

  1. 您正在加载XmlDocument,然后加载到XDocument。没有理由这样做。选择一个,最好是后者。

  2. 您调用doc.Load(@"CustomersDetail.xml");但不会捕获任何异常。如果该文件不存在,则此方法将抛出FileNotFoundException。 (我注意到the documentation没有明确说明这一点。这似乎是微软的疏忽。)另外,如果在程序的早期运行中,无效的XML被写入"CustomersDetail.xml",对doc.Load()的后续调用将抛出XmlException。 (例如,一个空文件是无效的XML。)所以你可能也想要捕获它。

  3. XmlDocument中,要检查是否尚未创建根节点,请检查XmlDocument.DocumentElement是否为null。在XDocument中,检查XDocument.Root是否为null

  4. 您应该将用户界面方法与“保存”方法分开,并删除重复的内嵌硬编码字符串,例如@"CustomersDetail.xml"

  5. InsertCustomer()中,long.Parse()可以针对不良用户输入抛出各种异常。您应该考虑处理这些例外情况。

  6. 因此:

    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; }
    
        internal const string XmlFileName = @"CustomersDetail.xml";
    
        private void AddToDB()
        {
            XDocument xdoc;
            if (!XDocumentExtensions.TryLoad(XmlFileName, out xdoc))
                // File does not exist.  Create it.
                xdoc = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XComment("LINQ To XML Demo"));
    
            if (xdoc.Root == null)
                xdoc.Add(new XElement("Customers"));
    
            xdoc.Root.Add(new XElement("Customer",
                            new XElement("CustId", CustId),
                            new XElement("Name", Name),
                            new XElement("MobileNo", MobileNo),
                            new XElement("Location", Location),
                            new XElement("Address", Address)));
    
            try
            {
                xdoc.Save(XmlFileName);
                Console.WriteLine("\n Added \n" + xdoc.ToString());
            }
            catch (Exception ex)
            {
                // No documented specific exception types from XDocument.Save() either.
                Debug.WriteLine(ex);
                Console.WriteLine(string.Format("Failed to write to XML file {0}", XmlFileName));
            }
        }
    
        // 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();
    
            AddToDB();
        }
    }
    

    使用

    public static class XDocumentExtensions
    {
        public static bool TryLoad(string fileName, out XDocument doc)
        {
            try
            {
                doc = XDocument.Load(fileName);
                return true;
            }
            catch (FileNotFoundException)
            {
                // File does not exist yet, so we must create it.
                doc = null;
            }
            catch (Exception ex)
            {
                // Some other internal error.
                // XDocument.Load() has no documented specific exception types :(
                // http://stackoverflow.com/questions/6904907/xdocument-loadxmlreader-possible-exceptions
                // So we could either catch these or pass them upwards.
                System.Diagnostics.Debug.WriteLine(ex);
                doc = null;
            }
            return false;
        }
    }