C#:XmlWriter虽然识别输入

时间:2016-12-19 22:12:23

标签: c# xml

我正在创建一个充当待办事项列表的程序。 'save'函数接受'Homework'结构列表,并使用格式化的XmlWriter将xml文件写入项目文件夹中的给定文件位置。它使用完整路径,而不是相对路径。  但是,尽管数据正确迭代(也已检查过),但数据似乎都没有保存到文件中。 保存例程读取:

static void SaveHomeworks(List<Homework> Tasks)
{
    XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()
    {
        Indent = true,
        IndentChars = "\t",
        NewLineOnAttributes = true
    };

    XmlWriter XMLWriter = XmlWriter.Create(Path, xmlWriterSettings);//Assigns the file to write to, given the settings of the writer.
    XMLWriter.WriteStartDocument();//starts writing the XML Document
    XMLWriter.WriteStartElement("Data");

    foreach (Homework ThisHomework in Tasks)
    {
        XMLWriter.WriteStartElement("Homework");//this is a nested element, one user in the collection of users      
        XMLWriter.WriteAttributeString("Title", ThisHomework.Title);
        XMLWriter.WriteAttributeString("Desc", ThisHomework.Description);
        XMLWriter.WriteAttributeString("Subject", ThisHomework.Subject);
        DateTime ThisDueDate = ThisHomework.DueDate;
        string Day = Convert.ToString(ThisDueDate.Day);
        string Month = Convert.ToString(ThisDueDate.Month);
        string Year = Convert.ToString(ThisDueDate.Year);
        XMLWriter.WriteAttributeString("DueDateDay", Day);
        XMLWriter.WriteAttributeString("DueDateMonth", Month);
        XMLWriter.WriteAttributeString("DueDateYear", Year);
        string Imp = Convert.ToString(ThisHomework.ImportanceLevel);
        XMLWriter.WriteAttributeString("Importance", Imp);
        if (ThisHomework.IsComplete == true)
        {
            XMLWriter.WriteAttributeString("IsComplete", "1");
        }
        else
        {
            XMLWriter.WriteAttributeString("IsComplete", "0");
        }
        XMLWriter.WriteEndElement();//this is the end of a "homework." (Still in the outer element "Data")...
    }
    XMLWriter.WriteEndDocument();//This closes ALL open elements regardless of nesting, but make sure you finish the current element!
    XMLWriter.Close();//closes the file itself.
}

HomeworkData.xml的属性是:

Build Action: Content Copy To Output Directory: Do not copy Custom Tool : (blank) Custom Tool Namespace : (blank) File Name : HomeworkData.xml Full Path :"c:\users\MY_ACCOUNT\documents\visual studio 2015\Projects\NewHomeworkManager\NewHomeworkManager\HomeworkData.xml"

如果有帮助,字符串'Path'是 c:\users\MY_ACCOUNT\documents\visual studio 2015\Projects\NewHomeworkManager\NewHomeworkManager\HomeworkData.xml - 相同。

我在Windows 10上运行VS 2015。

有什么明显的东西我做错了防止保存吗?它曾经工作,但似乎不再,我可能已经意外地更改了Visual Studio中的设置。任何指针都有帮助!

进一步编辑:删除了LoadHomeworksData信息,因为我有30k字符限制,人们说没关系。

这里也是在程序中创建新作业的方法。 (注意:日期输入为英文而非美国格式的输入,即DD / MM / YYYY)

static Homework AddNewHomework()
    {
        Console.Clear();
        Console.CursorVisible = true;
        var NewHomework = new Homework();
        Console.WriteLine("Please enter the name of the task.");
        NewHomework.Title = Console.ReadLine();
        Console.WriteLine("Please enter a description of the homework task.");
        NewHomework.Description = Console.ReadLine();
        Console.WriteLine("Please enter the subject it is from, if any.");
        NewHomework.Subject = Console.ReadLine();
        Console.Clear();
        Console.WriteLine("Please enter the due date for this piece of homework.\n Please use a '/' symbol to separate it out.");
        DateTime DueDate;
        while (true)
        {
            int[] numbers = new int[3];
            string DateToFormat = Console.ReadLine();
            try
            {
                string[] words = DateToFormat.Split('/');
                numbers[0] = int.Parse(words[0]);
                numbers[1] = int.Parse(words[1]);
                numbers[2] = int.Parse(words[2]);
            }
            catch
            {
                Console.WriteLine("Please use '/' symbols to separate the day, month and then year.\n No spaces please.");
            }
            if (numbers[2] != 0)
            {
                try
                {
                    DueDate = new DateTime(numbers[2], numbers[1], numbers[0]);
                    if (DueDate >= DateTime.Now)
                    {
                        break;
                    }
                    else
                    {
                        Console.WriteLine("Please enter a due date that hasn't already happened!");
                    }

                }
                catch
                {
                    Console.WriteLine("Please enter a valid date!");
                }
            }
        }
        NewHomework.DueDate = DueDate;
        Console.WriteLine("Please enter the importance of the homework, in a rating of 1 to 5.");
        while (true)
        {
            try
            {
                NewHomework.ImportanceLevel = int.Parse(Console.ReadLine());
                if (1 <= NewHomework.ImportanceLevel && NewHomework.ImportanceLevel <= 5)
                {
                    break;
                }
                else
                {
                    Console.WriteLine("Please enter a number between 1 and 5.");
                }
            }
            catch
            {
                Console.WriteLine("Please enter an integer from 1 to 5.");
            }
        }
        NewHomework.IsComplete = false;
        return NewHomework;
    }

这就是它在主循环中的调用方式:

case ConsoleKey.A:
                    Homework NewHomework = AddNewHomework();
                    Tasks.Add(NewHomework);
                    Console.Clear();
                    break;

1 个答案:

答案 0 :(得分:0)

方法SaveHomeworksLoadHomeworksData没有错误,当分别与有效List<Homework>和有效XML文件一起使用时,它们肯定有效。我已经通过LinqPad 5在Windows 10上成功使用了这两种方法。

我假设您在加载FileNotFound文件时遇到XML异常,因此返回一个空列表,然后创建您显示的XML内容。在xmlDoc.Load(Path);上的此方法中放置断点并检查路径的值,它可能在某种程度上无效。

我不能说为什么在没有看到这些方法的情况下修改列表是行不通的。我假设你丢失了对列表的引用,或者你不小心创建了一个空的。

这是一个手动创建家庭作业列表并将其传递给SaveHomeworks的示例,这样可以正常工作。

var list = new List<Homework>();

var one = new Homework()
{
    Title = "Title 1",
    Description = "Description",
    Subject = "Subject",
    DueDate = new DateTime(2016,1,1),
    ImportanceLevel = 1,
    IsComplete = false
};

var two = new Homework()
{
    Title = "Title 2",
    Description = "Description",
    Subject = "Subject",
    DueDate = new DateTime(2016,1,1),
    ImportanceLevel = 1,
    IsComplete = false
};

var three = new Homework()
{
    Title = "Title 3",
    Description = "Description",
    Subject = "Subject",
    DueDate = new DateTime(2016,1,1),
    ImportanceLevel = 1,
    IsComplete = false
};

list.Add(one);
list.Add(two);
list.Add(three);

SaveHomeworks(list);