如何只创建一次根标签
本文关键字:一次 标签 创建 | 更新日期: 2023-09-27 17:53:09
尝试从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'?>
和根元素wise
调用Load
(它将在现有文件的结束处离开流),然后调用Save
。不要在同一条流上这样做。您可以只是重新定位它,但如果新文档更短,那么您最终会遇到问题。(现在不会,将来可能会。)
我强烈建议你把它分成三个部分:
- 创建只读取和加载现有文档的流
- 修改内存中的文档
- 创建一个只写(截断现有文件)的流,并保存文档