C# xml.LoadData - 根级别的数据无效。第 1 行,位置 1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17795167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:29:49  来源:igfitidea点击:

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

c#xmlxml-parsingwix

提问by Chris

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:

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

XmlDocument xml = new XmlDocument();
try
{
    xml.LoadXml(myString);
}
catch (Exception ex)
{
    System.IO.File.WriteAllText(@"C:\text.txt", myString + "\r\n\r\n" + ex.Message);
    throw ex;
}

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

myString这是(如 的输出中所见text.txt

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

text.txtcomes out looking like this:

text.txt出来看起来像这样:

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

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

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

我需要解析这个 XML,以便我可以查看是否有任何错误。

Edit

编辑

This question is not a duplicate as marked. In that question the person asking the question was using LoadXmlto parse an XML file. I'm parsing a string, which is the correct use of LoadXml

这个问题不是标记的重复。在那个问题中,提出问题的人正在使用LoadXml解析 XML 文件。我正在解析一个字符串,这是正确的用法LoadXml

采纳答案by Amit Merin

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.

隐藏的字符可能是 BOM。问题的解释和解决方案可以在这里找到,归功于 James Schubert,基于 James Brankin 在此处找到的答案。

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);
}

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.

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

回答by Chris

The issue here was that myStringhad that header line. Either there was some hidden character at the beginning of the first line or the line itself was causing the error. I sliced off the first line like so:

这里的问题是myString有那个标题行。要么在第一行的开头有一些隐藏字符,要么是行本身导致了错误。我像这样切掉了第一行:

xml.LoadXml(myString.Substring(myString.IndexOf(Environment.NewLine)));

This solved my problem.

这解决了我的问题。

回答by Ringo

Use Load()method instead, it will solve the problem. See more

改用Load()方法,它会解决问题。查看更多

回答by pawciu

I Think that the problem is about encoding. That's why removing first line(with encoding byte) might solve the problem.

我认为问题在于编码。这就是为什么删除第一行(带有编码字节)可能会解决问题的原因。

My solution for Data at the root level is invalid. Line 1, position 1.in XDocument.Parse(xmlString)was replacing it with XDocument.Load( new MemoryStream( xmlContentInBytes ) );

在根级别数据的解决方案无效。第 1 行,位置 1.inXDocument.Parse(xmlString)将其替换为XDocument.Load( new MemoryStream( xmlContentInBytes ) );

I've noticed that my xml string looked ok:

我注意到我的 xml 字符串看起来不错:

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

but in different text editor encoding it looked like this:

但在不同的文本编辑器编码中,它看起来像这样:

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

At the end i did not need the xml string but xml byte[]. If you need to use the string you should look for "invisible" bytes in your string and play with encodings to adjust the xml content for parsing or loading.

最后我不需要xml字符串而是xml字节[]。如果您需要使用字符串,您应该在字符串中查找“不可见”字节并使用编码来调整用于解析或加载的 xml 内容。

Hope it will help

希望它会有所帮助

回答by MikeMajara

Save your file with different encoding:

使用不同的编码保存文件:

File > Save file as... > Save as UTF-8 without signature.

文件 > 将文件另存为... > 另存为 UTF-8,无需签名。

In VS 2017 you find encoding as a dropdown next to Save button.

在 VS 2017 中,您可以在“保存”按钮旁边的下拉列表中找到编码。

回答by Mister Cook

If your xml is in a string use the following to remove any byte order mark:

如果您的 xml 在字符串中,请使用以下内容删除任何字节顺序标记:

        xml = new Regex("\<\?xml.*\?>").Replace(xml, "");

回答by Shubhasish Bhunia

I have found out one of the solutions. For your code this could be as follows -

我已经找到了解决方案之一。对于您的代码,这可能如下 -

XmlDocument xml = new XmlDocument();
try
{
    // assuming the location of the file is in the current directory 
    // assuming the file name be loadData.xml
    string myString = "./loadData.xml";
    xml.Load(myString);
}
catch (Exception ex)
{
    System.IO.File.WriteAllText(@"C:\text.txt", myString + "\r\n\r\n" + ex.Message);
    throw ex;
}

回答by Michael Planer

I've solved this issue by directly editing the byte array. Collect the UTF8 preamble and remove directly the header. Afterward you can transform the byte[]to a string with GetString method, see below. The \r and \t I've removed as well, just as precaution.

我通过直接编辑字节数组解决了这个问题。收集 UTF8 前导码并直接删除标头。之后,您可以使用 GetString 方法将 byte[] 转换为字符串,请参见下文。\r 和 \t 我也删除了,作为预防措施。

XmlDocument configurationXML = new XmlDocument();
List<byte> byteArray = new List<byte>(webRequest.downloadHandler.data);

foreach(byte singleByte in Encoding.UTF8.GetPreamble())
{
     byteArray.RemoveAt(byteArray.IndexOf(singleByte));
}
string xml = System.Text.Encoding.UTF8.GetString(byteArray.ToArray());
       xml = xml.Replace("\r", "");
       xml = xml.Replace("\t", "");

回答by Raj

if we are using XDocument.Parse(@""). Use @ it resolves the issue.

如果我们使用 XDocument.Parse(@"")。使用@它可以解决问题。