提问人:KillerToaster 提问时间:10/31/2023 最后编辑:KillerToaster 更新时间:11/1/2023 访问量:88
xml.LoadData 根级别的数据无效,第 1 行,位置 1。现有解决方案无济于事
xml.LoadData Data at root level is invalid, line 1, pos 1. Existing solutions not helping
问:
我正在尝试将我从字符串构建的 xml 文件保存到本地内存中,App_Data C# Web 服务应用程序。尽管查看了以前的堆栈解决方案,但我还是收到此错误:
根级别的数据无效。第 1 行,位置 1。
我尝试保存到文件的 xml 是一个简单的节点列表。
这是通过本地主机上的 ASP.NET 应用程序进行测试的。(这可能会影响 Web 服务应用程序吗?不过,我认为这是不可能的)
我尝试实现前两个堆栈问题的解决方案:
这是我尝试的第一个代码
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>
答:
1赞
QI You
11/1/2023
#1
"根级数据无效,第 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);
})
评论
0赞
Jonas Høgh
11/1/2023
调用 xml 字符串时,第一行的第一个字符将是文档以转义元素开头的字符 - 无论编码和 BOM 如何,这都永远不会起作用SecurityElement.Escape
&
<Books>
评论
xmlWithEscapedCharacters
- 1
SecurityElement.Escape
xmlDocument.LoadXml