我一直在用一个项目学习C#的XML,但是我一直在学习InvalidOperationException。我把代码放在下面
XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
writer.WriteStartDocument(true);
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
writer.WriteStartElement("User Info");
writer.WriteStartElement("Name");
writer.WriteString(userName);
writer.WriteEndElement();
writer.WriteStartElement("Tutor Name");
writer.WriteString(tutorName);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteStartElement("Course Data"); /*This is where the exception points to*/
foreach (UserCourse c in courses)
{
String cn = c.Name;
writer.WriteStartElement(cn);
foreach (UserUnit u in c.Units)
{
writer.WriteStartElement(u.Name.ToString());
foreach (UserObjective o in u.Objectives)
{
writer.WriteStartElement(o.Name.ToString());
writer.WriteString(o.Score.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
也许有人能看出我做错了什么。我感谢任何帮助!
答案 0 :(得分:3)
答案 1 :(得分:1)
“用户信息”和“课程数据”是不同的实体。如果是这样,我认为你可以将它们封装在一个实体中。
XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
writer.WriteStartDocument(true);
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
writer.WriteStartElement("My Entity"); /* It is a biggest one*/
writer.WriteStartElement("User Info");
writer.WriteStartElement("Name");
writer.WriteString(userName);
writer.WriteEndElement();
writer.WriteStartElement("Tutor Name");
writer.WriteString(tutorName);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteStartElement("Course Data"); /*This is where the exception points to*/
foreach (UserCourse c in courses)
{
String cn = c.Name;
writer.WriteStartElement(cn);
foreach (UserUnit u in c.Units)
{
writer.WriteStartElement(u.Name.ToString());
foreach (UserObjective o in u.Objectives)
{
writer.WriteStartElement(o.Name.ToString());
writer.WriteString(o.Score.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();