xml.LoadData - 根级别的数据无效.第 1 行,位置 1 [英] xml.LoadData - Data at the root level is invalid. Line 1, position 1

查看:30
本文介绍了xml.LoadData - 根级别的数据无效.第 1 行,位置 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析 WiX 安装程序中的一些 XML.XML 将是我从 Web 服务器返回的所有错误的对象.我在使用此代码的问题标题中收到错误:

I'm trying to parse some XML inside a WiX installer. The XML would be an object of all my errors returned from a web server. I'm getting the error in the question title with this code:

XmlDocument xml = new XmlDocument();
try
{
    xml.LoadXml(myString);
}
catch (Exception ex)
{
    System.IO.File.WriteAllText(@"C:	ext.txt", myString + "

" + ex.Message);
    throw ex;
}

myString 是这个(如 text.txt 的输出所示)

myString is this (as seen in the output of text.txt)

<?xml version="1.0" encoding="utf-8"?>
<Errors></Errors>

text.txt 看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<Errors></Errors>

Data at the root level is invalid. Line 1, position 1.

我需要解析此 XML,以便查看是否有任何错误.

I need this XML to parse so I can see if I had any errors.

推荐答案

隐藏的字符可能是 BOM.问题的解释和解决方法可以在此处,归功于 James Schubert,基于 James Brankin 的回答发现 此处.

The hidden character is probably BOM. The explanation to the problem and the solution can be found here, credits to James Schubert, based on an answer by James Brankin found here.

虽然上一个答案确实删除了隐藏字符,但它也删除了整个第一行.更精确的版本是:

Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
    xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}

我在从 Azure blob 获取 XSLT 文件并将其加载到 XslCompiledTransform 对象时遇到了这个问题.在我的机器上,该文件看起来不错,但在将其作为 blob 上传并取回后,添加了 BOM 字符.

I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object. On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added.

这篇关于xml.LoadData - 根级别的数据无效.第 1 行,位置 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆