简体   繁体   English

尝试创建xml文件时出错

[英]Error while trying to create xml file

The following is my code: 以下是我的代码:

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

I'm getting the following error: 我收到以下错误:

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

Why am I getting this error? 为什么会出现此错误?

The following is the error details: 以下是错误的详细信息:

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: 

I am using Visual Studio 2010 Ultimate. 我正在使用Visual Studio 2010 Ultimate。

You should remove the writer.WriteStartDocument(); 您应该删除writer.WriteStartDocument(); and writer.WriteEndDocument(); writer.WriteEndDocument(); from the using block. using块。 In that block, you are appending to an element, and you cannot start an XML document inside an element. 在该块中,您将追加到元素,并且无法元素启动XML文档。

If you just want to create a new XML document, I would suggest doing this: 如果您只想创建一个新的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"); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM