XML read write ('System.Xml.XmlException is thrown)

本文关键字:XmlException Xml is thrown System write read XML | 更新日期: 2023-09-27 18:28:39

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 数据库

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 中发生了类型为"System.Xml.XmlException"的未处理异常.dll

其他信息:缺少根元素。

帮帮我

XML read write ('System.Xml.XmlException is thrown)

你在这里有几个问题:

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

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

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

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

  5. InsertCustomer()中,long.Parse()可以抛出各种错误的用户输入异常。 应考虑处理这些异常。

因此:

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