??XML ...>如果字符串开始以&lt解析XML字符串XML文档失败;部分 [英] Parsing xml string to an xml document fails if the string begins with <?xml... ?> section

查看:230
本文介绍了??XML ...>如果字符串开始以&lt解析XML字符串XML文档失败;部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文件,开始时是这样的:

I have an XML file begining like this:

<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition">
  <DataSources>

当我运行下面的code:

When I run following code:

byte[] fileContent = //gets bytes
            string stringContent = Encoding.UTF8.GetString(fileContent);
            XDocument xml = XDocument.Parse(stringContent);

我得到以下XmlException:

I get following XmlException:

在根级别的数据无效。   行1,位置1。

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

切割出的版本和编码节点解决了这个问题。为什么?如何正确处理这个XML?

Cutting out the version and encoding node fixes the problem. Why? How to process this xml correctly?

推荐答案

如果你只有字节,你既可以加载到字节流:

If you only have bytes you could either load the bytes into a stream:

XmlDocument oXML;

using (MemoryStream oStream = new MemoryStream(oBytes))
{
  oXML = new XmlDocument();
  oXML.Load(oStream);
}

或者你可以在加载XML之前转换成字节的字符串(你知道的编码presuming):

Or you could convert the bytes into a string (presuming that you know the encoding) before loading the XML:

string sXml;
XmlDocument oXml;

sXml = Encoding.UTF8.GetString(oBytes);
oXml = new XmlDocument();
oXml.LoadXml(sXml);

我已经证明我的例子作为.NET 2.0兼容的,如果你使用的是.NET 3.5,你可以使用的XDocument 而不是的XmlDocument

加载字节到流:

XDocument oXML;

using (MemoryStream oStream = new MemoryStream(oBytes))
using (XmlTextReader oReader = new XmlTextReader(oStream))
{
  oXML = XDocument.Load(oReader);
}

在转换成字节的字符串:

Convert the bytes into a string:

string sXml;
XDocument oXml;

sXml = Encoding.UTF8.GetString(oBytes);
oXml = XDocument.Parse(sXml);

这篇关于??XML ...&GT;如果字符串开始以&lt解析XML字符串XML文档失败;部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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