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

前端 未结 4 1152
有刺的猬
有刺的猬 2021-01-11 23:02

I am getting \"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\" error

相关标签:
4条回答
  • 2021-01-11 23:35

    As the error states, the first five characters of an XML document should be <?xml. No ifs, ands or buts. The comments you have above the opening XML tag are illegal; they must go inside the XML tag (because the comment structure is itself defined by the XML standard and so is meaningless outside the main XML tags).

    EDIT: Something like this should be able to rearrange the rows, given the file format from the 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();
       } 
    
    0 讨论(0)
  • 2021-01-11 23:41

    That is not valid XML.

    As the error clearly states, the XML declaration (<?xml ... ?>) must come first.

    0 讨论(0)
  • 2021-01-11 23:41

    Don't put any comments in the beginning of your file!

    0 讨论(0)
  • 2021-01-11 23:44

    I'm using the following function to remove whitespace from 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);
    
        }
    
    0 讨论(0)
提交回复
热议问题