0

试图从 FileStreame Writer 类的 xml 文件创建 XML 文件,但它给了我一个错误Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it.

它创建<?xml version='1.0' encoding='utf-8' standalone='yes'?>和根元素标签两次我的代码

using (FileStream fileStream = new FileStream(_logFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    string currentDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                    xmlDoc.Load(fileStream);
                    XmlElement newelement = xmlDoc.CreateElement("LogData");
                    XmlElement xmlLogID = xmlDoc.CreateElement("LogID");
                    XmlElement xmlLogDateTime = xmlDoc.CreateElement("LogDateTime");
                    XmlElement xmlLogType = xmlDoc.CreateElement("LogType");
                    XmlElement xmlLogFlag = xmlDoc.CreateElement("LogFlag");
                    XmlElement xmlLogApplication = xmlDoc.CreateElement("LogApplication");
                    XmlElement xmlLogModule = xmlDoc.CreateElement("LogModule");
                    XmlElement xmlLogLocation = xmlDoc.CreateElement("LogLocation");
                    XmlElement xmlLogText = xmlDoc.CreateElement("LogText");
                    XmlElement xmlLogStackTrace = xmlDoc.CreateElement("LogStackTrace");

                    xmlLogID.InnerText = _logIDPrefix + currentDateTime + randomNumber;
                    xmlLogDateTime.InnerText = currentDateTime;
                    xmlLogType.InnerText = ((LogTypes)Convert.ToInt32(logType)).ToString();
                    xmlLogFlag.InnerText = logFlag;
                    xmlLogApplication.InnerText = _logApplication;
                    xmlLogModule.InnerText = logModule;
                    xmlLogLocation.InnerText = logLocation;
                    xmlLogText.InnerText = logText;
                    xmlLogStackTrace.InnerText = logStackTrace;

                    newelement.AppendChild(xmlLogID);
                    newelement.AppendChild(xmlLogDateTime);
                    newelement.AppendChild(xmlLogType);
                    newelement.AppendChild(xmlLogFlag);
                    newelement.AppendChild(xmlLogApplication);
                    newelement.AppendChild(xmlLogModule);
                    newelement.AppendChild(xmlLogLocation);
                    newelement.AppendChild(xmlLogText);

                    xmlDoc.DocumentElement.AppendChild(newelement);
                    xmlDoc.Save(fileStream);

这个代码被执行了不止一次,但我只是想防止创建<?xml version='1.0' encoding='utf-8' standalone='yes'?>和根元素 twise

4

1 回答 1

0

您正在调用Load(这会将流留在现有文件的末尾),然后调用Save. 不要在同一个流上这样做。您可以重新定位它,但如果新文档较短,您最终会遇到问题。(现在不会,但将来可能会。)

我强烈建议您将其分为三个部分:

  • 创建一个只读取并加载现有文档的流
  • 修改内存中的文档
  • 创建一个只写入的流(截断现有文件),并保存文档
于 2013-01-15T13:37:54.340 回答