You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Web服务保存XML报错:根级别数据无效(行1,位置1)

XML保存报错:“Data at the root level is invalid. Line 1, position 1.” 解决遇阻

我尝试将字符串构建的XML保存到C# Web服务应用的App_Data本地目录中,查阅相关解决方案后仍遇到错误:Data at the root level is invalid. Line 1, position 1.

要保存的XML是简单节点列表,当前通过本地ASP.NET应用测试(不确定是否会影响Web服务应用)。

我尝试了以下几种处理方式:

最初尝试的代码

XmlDocument doc = new XmlDocument();
var xmlWithEscapedCharacters = SecurityElement.Escape(finalXML); //finalXML是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);
}

自行尝试的循环处理代码(导致超时错误)

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

编辑补充:以下是我要添加节点的有效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>

内容的提问来源于stack exchange,提问作者KillerToaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 04:10:58