xml.LoadData 根级别的数据无效,第 1 行,位置 1。现有解决方案没有帮助

问题描述 投票:0回答:1

我正在尝试将我从字符串构建的 xml 文件保存到 C# Web 服务应用程序的 App_Data 中的本地内存中。尽管查看了以前的堆栈解决方案,我还是收到了此错误:

根级别的数据无效。 1 号线,1 号位置。

我尝试保存到文件的 xml 是一个简单的节点列表。

这是通过本地主机上的 ASP.NET 应用程序进行测试的。 (这可能会影响网络服务应用程序吗?不过我认为这是不可能的)

我尝试实施前两个堆栈问题的解决方案:

  1. 第一个
  2. 第二个

这是我尝试的第一个代码

XmlDocument doc = new XmlDocument();
var xmlWithEscapedCharacters = SecurityElement.Escape(finalXML); //finalXML is of type string

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if((xmlWithEscapedCharacters.StartsWith(_byteOrderMarkUtf8))
{
    var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length - 1;
    xmlWithEscapedCharacters = xmlWithEscapedCharacters.Remove(0, lastIndexOfUtf8);
}

doc.LoadXml(xmlWithEscapedCharacters);
doc.PreserveWhitespace = true;
doc.Save("Parks.xml");

然后我从第二个解决方案中尝试了这个

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if(xmlWithEscapedCharacters[0] == '\ufeff')
{
    var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length - 1;
    xmlWithEscapedCharacters = xmlWithEscapedCharacters.Remove(0, lastIndexOfUtf8);
}

然后我什至认为文件开头可能有多个 BOM 并尝试过

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
while (xmlWithEscapedCharacters[0] == '\ufeff')
{
    var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length - 1;
    xmlWithEscapedCharacters = xmlWithEscapedCharacters.Remove(0, lastIndexOfUtf8);
}

这导致超时错误。

我对这个看似相当简单的问题感到困惑。

编辑 2(错误的 XML 文件,抱歉): 以下是有效 XML 文件的示例。我正在使用此代码添加一个节点。

<Books>
<Book Cover="Paper back">
    <ISBN>978-0132309981</ISBN>
    <Title>Operating Systems Internals and Design Principles</Title>
    <Author>
        <Name>
            <First>William</First>
            <Last>Stallings</Last>
        </Name>
        <Contact Office="BY101">
            <Phone>480-965-0000</Phone>
        </Contact>
    </Author>
    <Publisher>Prentice Hall</Publisher>
    <Year Edition="7">2011</Year>
</Book>
</Books>
c# asp.net xml wcf
1个回答
0
投票

根级别的数据无效,第1行,位置1”通常是由以下原因引起的 1.XML文件不是用UTF-8编码的 2.XML文件有BOM字符。

我认为您可以使用 SecurityElement.Escape(String) 方法将无效字符替换为有效字符后检查是否有 BOM 字符。

 public string UTF8Str(string str)
        {
           
            byte[] buffer = File.ReadAllBytes(str);
         
            byte[] bomBuffer = { 0xef, 0xbb, 0xbf };
            if (buffer[0] == bomBuffer[0]
                && buffer[1] == bomBuffer[1]
                && buffer[2] == bomBuffer[2])
            { 
                var result = new UTF8Encoding(false).GetString(buffer);
                result = "<" + result.Substring(result.IndexOf('<') + 1);
                return result;
            }
            return Encoding.UTF8.GetString(buffer);
        })
© www.soinside.com 2019 - 2024. All rights reserved.