【问题标题】:Error: The XML declaration must be the first node in the document错误:XML 声明必须是文档中的第一个节点
【发布时间】:2012-08-14 19:21:46
【问题描述】:

我在尝试加载 xml 时收到“意外的 XML 声明。XML 声明必须是文档中的第一个节点,并且在它之前不允许出现空白字符”错误。下面给出了我的 C# 代码和 XML 文件的内容。 XML 定义存在于 xml 文件的第 6 行,因此存在错误。

我无法控制 xml 文件中的内容,所以我如何使用 C# 编辑/重写它,以便首先出现 xml 声明,然后 cmets 加载它而不会出现任何错误!

//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"?>
-----

【问题讨论】:

  • 我相信&lt;?...?&gt;应该在cmets之前。注释语法是 XML 规范的一部分
  • 有没有办法编辑 xml 文件,以便首先定义,然后使用 c# 的 cmets,以便我可以加载 xml 文档以进行进一步处理..
  • 这不是来自 IEX 吗?我只是遇到了同样的事情。令人沮丧。

标签: c# .net xml


【解决方案1】:

如错误所述,XML 文档的前五个字符应为&lt;?xml。没有如果,ands 或 buts。您在开始 XML 标记上方的 cmets 是非法的;它们必须放在 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();
   } 

【讨论】:

  • 是的,你是对的,cmets 应该只在 xml 定义之后出现,但我得到了该格式的所有 xml 文件,我必须加载 x​​ml。有没有办法编辑 xml 文档,以便
  • 是的,您必须使用普通的 FileStream 打开文件,使用 TextReader 读取它以提取原始 SQL,重新排列文件的行,使 &lt;?xml ... ?&gt; 标记在前,然后在使用 XmlReader 将其拉入之前将其写回。
  • 谢谢基思!我已经尝试过您的建议,但无法成功重新排列文件的行,因此如果您能帮助我编写该代码,那将对我有很大帮助。
  • 完美的基思!它的工作就像魅力!非常感谢您的快速响应,而其他人则忽略了它。
【解决方案2】:

这不是有效的 XML。

正如错误明确指出的那样,XML 声明 (&lt;?xml ... ?&gt;) 必须首先出现

【讨论】:

  • 我无法控制 xml 文件中的内容。我知道根据标准它不是有效的 xml,但我需要使用 c# 加载给定的 xml 以进行进一步处理。
【解决方案3】:

我正在使用以下函数从 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);

    }

【讨论】:

    【解决方案4】:

    不要将任何 cmets 放在文件的开头!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 2010-09-09
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      相关资源
      最近更新 更多