尝试从FileStreame Writer类的xml文件创建XML文件,但它给我一个错误lile 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
答案 0 :(得分:0)
您正在调用Load
(将流保留在现有文件的 end ),然后调用Save
。不要在同一个流上执行此操作。您可以重新定位它,但如果新文档更短,您最终会遇到问题。 (现在不会,但也许将来。)
我强烈建议您将其分为三个部分: