尝试创建xml文件时出错

时间:2013-08-01 09:35:53

标签: c# xml visual-studio-2010 c#-4.0

以下是我的代码:

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

namespace xml1
{
class Program
{
    Employee[] employees = new Employee[1];
    class Employee
    {
        int _id;
        string _firstName;
        string _lastName;
        int _salary;

        public Employee(int id, string firstName, string lastName, int salary)
        {
            this._id = id;
            this._firstName = firstName;
            this._lastName = lastName;
            this._salary = salary;
        }

        public int Id { get { return _id; } }
        public string FirstName { get { return _firstName; } }
        public string LastName { get { return _lastName; } }
        public int Salary { get { return _salary; } }
    }
    void CreateXML()
    {
        //XmlWriter writer = XmlWriter.Create(@"C:\Users\simonjef\Desktop\employees.xml");
        XmlDocument doc=new XmlDocument();
        doc.Load(@"C:\Users\simonjef\Desktop\Emp.xml");

      //  XmlWriter writer = XmlWriter.Create(File.Open(@"C:\Users\simonjef\Desktop\employees.xml", FileMode.Open));
        if (!File.Exists(@"C:\Users\simonjef\Desktop\Emp.xml"))
        {
            XmlTextWriter textWritter = new XmlTextWriter(@"C:\Users\simonjef\Desktop\Emp.xml", null);
            textWritter.WriteStartDocument();
            textWritter.WriteStartElement("Employees");
            textWritter.WriteEndElement();
            textWritter.WriteEndDocument();
            textWritter.Close();
        }

        using (XmlWriter writer = doc.DocumentElement.CreateNavigator().AppendChild())
        {             
            writer.WriteStartDocument();
            writer.WriteStartElement("Employees9");

            foreach (Employee employee in employees)
            {
                writer.WriteStartElement("Employee");
                writer.WriteAttributeString("ID", employee.Id.ToString());
                writer.WriteAttributeString("FirstName", employee.FirstName);
                writer.WriteAttributeString("LastName", employee.LastName);
                writer.WriteAttributeString("Salary", employee.Salary.ToString());
                //writer.WriteElementString("ID", employee.Id.ToString());

                //writer.WriteElementString("FirstName", employee.FirstName);
                //writer.WriteElementString("LastName", employee.LastName);
                //writer.WriteElementString("Salary", employee.Salary.ToString());

                //writer.WriteEndElement();
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
           writer.WriteEndDocument();

            doc.Save(@"C:\Users\simonjef\Desktop\Emp.xml"); 
        }
    }
    void AssignValues()
    {
        // Employee[] employees;
        employees[0] = new Employee(1, "David", "Smith", 10000);
        Array.Resize(ref employees, 2);
        employees[1] = new Employee(3, "Mark", "Drinkwater", 30000);
        Array.Resize(ref employees, 3);
        employees[2] = new Employee(4, "Norah", "Miller", 20000);
        Array.Resize(ref employees, 4);
        employees[3] = new Employee(12, "Cecil", "Walker", 120000);
    }
    static void Main(string[] args)
    {
        Program p = new Program();
        p.AssignValues();
        p.CreateXML();         
    }
}
}

我收到以下错误:

WriteStartDocument cannot be called on writers created with ConformanceLevel.Fragment.

为什么我收到此错误?

以下是错误详情:

System.InvalidOperationException was unhandled
  Message=The Writer is closed or in error state.
  Source=System.Xml
  StackTrace:
       at System.Xml.XmlWellFormedWriter.AdvanceState(Token token)
       at System.Xml.XmlWellFormedWriter.WriteStartDocumentImpl(XmlStandalone standalone)
       at System.Xml.XmlWellFormedWriter.WriteStartDocument()
       at xml1.Program.CreateXML() in C:\Users\simonjef\Documents\Visual Studio 2010\Projects\xml1\xml1\Program.cs:line 54
       at xml1.Program.Main(String[] args) in C:\Users\simonjef\Documents\Visual Studio 2010\Projects\xml1\xml1\Program.cs:line 98
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

我正在使用Visual Studio 2010 Ultimate。

1 个答案:

答案 0 :(得分:1)

您应该从writer.WriteStartDocument();块中删除writer.WriteEndDocument();using。在该块中,您将附加到元素,并且无法在元素中启动XML文档

如果您只想创建一个新的XML文档,我建议您这样做:

XmlDocument doc=new XmlDocument();
doc.LoadXml("<Employees9 />");

using (XmlWriter writer = doc.DocumentElement.CreateNavigator().AppendChild())
{
        foreach (Employee employee in employees)
        {
            writer.WriteStartElement("Employee");
            writer.WriteAttributeString("ID", employee.Id.ToString());
            writer.WriteAttributeString("FirstName", employee.FirstName);
            writer.WriteAttributeString("LastName", employee.LastName);
            writer.WriteAttributeString("Salary", employee.Salary.ToString());

            writer.WriteEndElement();
        }

        doc.Save(@"C:\Users\simonjef\Desktop\Account.xml"); 
}