簡體   English   中英

錯誤:XML聲明必須是文檔中的第一個節點

[英]Error: The XML declaration must be the first node in the document

嘗試加載xml時,出現“意外XML聲明。XML聲明必須是文檔中的第一個節點,並且不允許在其之前出現空白字符”錯誤。 我的C#代碼和XML文件的內容都在下面給出。 XML定義存在於xml文件的第6行中,因此會出現錯誤。

我無法控制xml文件中的內容,因此如何使用C#編輯/重寫該文件,使得首先出現xml聲明,然后進行注釋以加載它而沒有任何錯誤!

//xmlFilepath is the path/name of the xml file passed to this function
static function(string xmlFilepath)
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;
readerSettings.IgnoreWhitespace = true;
XmlReader reader = XmlReader.Create(XmlFilePath, readerSettings);
XmlDocument xml = new XmlDocument();
xml.Load(reader);
}

XmlDoc.xml

<!-- Customer ID: 1 -->
<!-- Import file: XmlDoc.xml -->
<!-- Start time: 8/14/12 3:15 AM -->
<!-- End time: 8/14/12 3:18 AM -->

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
-----

由於錯誤狀態,XML文檔的前五個字符應為<?xml 沒有,如果不是,而是。 您在XML開頭標簽上方的注釋是非法的; 它們必須放在XML標記內(因為注釋結構本身是由XML標准定義的,因此在主要XML標記之外毫無意義)。

編輯:給定OP中的文件格式,類似這樣的事情應該能夠重新排列行:

var lines = new List<string>();

using (var fileStream = File.Open(xmlFilePath, FileMode.Open, FileAccess.Read))
   using(var reader = new TextReader(fileStream))
   {
      string line;
      while((line = reader.ReadLine()) != null)
         lines.Add(line);
   }   

var i = lines.FindIndex(s=>s.StartsWith("<?xml"));
var xmlLine = lines[i];
lines.RemoveAt(i);
lines.Insert(0,xmlLine);

using (var fileStream = File.Open(xmlFilePath, FileMode.Truncate, FileAccess.Write)
   using(var writer = new TextWriter(fileStream))
   {
      foreach(var line in lines)
         writer.Write(line);

      writer.Flush();
   } 

那是無效的XML。

正如錯誤明確指出的那樣,必須首先聲明XML聲明( <?xml ... ?> )。

我正在使用以下功能從xml中刪除空格:

public static void DoRemovespace(string strFile)
    {
        string str = System.IO.File.ReadAllText(strFile);
        str = str.Replace("\n", "");
        str = str.Replace("\r", "");
        Regex regex = new Regex(@">\s*<");
        string cleanedXml = regex.Replace(str, "><");
        System.IO.File.WriteAllText(strFile, cleanedXml);

    }

不要在文件開頭添加任何評論!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM