【问题标题】:XML read write ('System.Xml.XmlException is thrown)XML 读写('System.Xml.XmlException 被抛出)
【发布时间】:2016-04-06 12:43:06
【问题描述】:
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”类型的未处理异常

附加信息:缺少根元素。

帮帮我

【问题讨论】:

  • 当您尝试运行该行时文件是什么样的?
  • 文件是空的
  • 那么看来错误信息是正确的。有空文件怎么办?
  • 你的代码对我有用,虽然我把保存到StringWriter。这有什么意义?
  • @SentilSebastian - 您的异常可能是因为在之前的程序运行中,您创建了无效的 XML 文件。

标签: c# xml


【解决方案1】:

这里有几个问题:

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

  2. 您调用了doc.Load(@"CustomersDetail.xml");,但没有捕获任何抛出的异常。如果文件不存在,此方法将抛出FileNotFoundException。 (我注意到the documentation 没有明确说明这一点。这似乎是微软的疏忽。)此外,如果在您的程序的早期运行中,无效的 XML 被写入"CustomersDetail.xml",随后调用@ 987654330@ 将抛出一个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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多