gpt4 book ai didi

C# XML : System. InvalidOperationException

转载 作者:数据小太阳 更新时间:2023-10-29 03:01:48 24 4
gpt4 key购买 nike

我一直在通过一个项目学习 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();

也许有人能看出我做错了什么。感谢您的帮助!

最佳答案

XML 元素名称不能包含空格。

引用XML Naming Rules .

另外,您似乎应该有一个根元素。像 CourseData 应该在 UserInfo 里面。

结帐 Fiddle

关于C# XML : System. InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30972932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com