创建Linq XML文档时,"非空白字符无法添加到内容"

use*_*168 2 c# xml linq

好吧,我正在通过这样做来缓存内存中的文件

byte[] file = System.IO.File.ReadAllBytes("test.xml");
Run Code Online (Sandbox Code Playgroud)

然后我会尝试从该缓冲区创建一个xml文档,如下所示:

System.IO.MemoryStream stream = new System.IO.MemoryStream(file);
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(stream);
System.Xml.Linq.XDocument xPartDocument = new System.Xml.Linq.XDocument(reader); 
Run Code Online (Sandbox Code Playgroud)

但这无法创建具有以下异常的文档:

A first chance exception of type 'System.ArgumentException' occurred in System.Xml.Linq.dll

Additional information: Non white space characters cannot be added to content.
Run Code Online (Sandbox Code Playgroud)

然而,'读者'看起来不对,即在本地人中它有'无'作为值:

  • reader {None} System.Xml.XmlTextReader

'file'字节数组变量有11个字节,看起来像标题(我假设这只是txt文件头?):

0x0393B148  58 35 59 71  X5Yq 
0x0393B14C  dc 67 01 00  Üg.. 
0x0393B150  ef bb bf 3c  < 
0x0393B154  3f 78 6d 6c  ?xml 
0x0393B158  20 76 65 72   ver
Run Code Online (Sandbox Code Playgroud)

任何帮助非常感谢.

谢谢

Jon*_*eet 6

如注释中所述,前8个字节看起来不属于XML文件的开头.接下来的三个字节是UTF-8 BOM,很好.你应该弄清楚那8个字节来自哪里,以及你是否应该总是期望它们在那里.

如果他们总是在那里并且你希望他们在那里,最简单的解决方法就是在阅读之前移动流:

MemoryStream stream = new MemoryStream(file);
stream.Position = 8;
XDocument doc = XDocument.Load(stream);
Run Code Online (Sandbox Code Playgroud)

或者,不首先加载所有数据:

XDocument doc;
using (Stream input = File.OpenRead("test.xml"))
{
    input.Position = 8;
    doc = XDocument.Load(input);
}
Run Code Online (Sandbox Code Playgroud)