动态地我试图通过c#代码创建xml文件,但得到以下异常:
XMLException未处理'/'是一个意外的令牌。预期的标记是'='。第4行,第18位。
这是我的代码:
string docAuthor = document.Info.Author.ToString();
string docCreationDate = document.Info.CreationDate.ToString();
StringWriter stringwriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter);
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument();
xmlTextWriter.WriteStartElement("root");
xmlTextWriter.WriteStartElement("information");
xmlTextWriter.WriteElementString("Author Name", docAuthor.ToString());
xmlTextWriter.WriteElementString("Creation Date", docCreationDate.ToString());
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteEndDocument();
XmlDocument docSave = new XmlDocument();
docSave.LoadXml(stringwriter.ToString());
//write the path where you want to save the Xml file
docSave.Save(@"C:\Information.xml");
答案 0 :(得分:3)
XML elements cannot have spaces
。删除Author Name
和Creation Date
之间的空格。它应该是 -
xmlTextWriter.WriteElementString("AuthorName", docAuthor.ToString());
xmlTextWriter.WriteElementString("CreationDate", docCreationDate.ToString());
答案 1 :(得分:0)
您需要调用Flush()
来清除作者的内部缓冲区
在此之前,支持StringWriter
将有半个书面文件。
但是,你根本不应该这样做;您应该直接保存到FileStream
。