Xamarin Forms EpubReader解析EPUB遇XML版本校验聚合异常
已实现的业务逻辑
在Xamarin Forms开发场景下,已经完成了以下功能:将远程EPUB文件的URL转换为可读取的流、解析EPUB书籍内容,同时将文件对应的字节数组保存到本地文档目录。核心实现代码如下:
Stream stream; HttpClient client = new HttpClient(); var response = await client.GetAsync(fileUrl); stream = await response.Content.ReadAsStreamAsync(); epubBook = EpubReader.ReadBook(stream); // 保存文件到本地目录 byte[] bytes = await response.Content.ReadAsByteArrayAsync(); string filename = Path.GetFileName(fileUrl); var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var filePath = Path.Combine(folderPath, filename); File.WriteAllBytes(filePath, bytes);
这套逻辑可以正常处理绝大多数EPUB文件,但加载部分远程文件时,会抛出System.AggregateException聚合异常。触发异常的直接表现为底层XML解析器无法识别EPUB内部XML文件声明的1.1版本头。
异常详情
System.AggregateException: 发生一个或多个错误。(版本号“1.1”无效,位于第1行第16位。) ---> System.Xml.XmlException: 版本号“1.1”无效,位于第1行第16位。
at System.Xml.XmlTextReaderImpl.Throw (System.Exception e) [0x00027] in <0757e7484a1349cca3b4558c721885b2>:0
at System.Xml.XmlTextReaderImpl.Throw (System.String res, System.String arg) [0x00029] in <0757e7484a1349cca3b4558c721885b2>:0
at System.Xml.XmlTextReaderImpl.ParseXmlDeclaration (System.Boolean isTextDecl) [0x0061f] in <0757e7484a1349cca3b4558c721885b2>:0
at System.Xml.XmlTextReaderImpl.Read () [0x000c6] in <0757e7484a1349cca3b4558c721885b2>:0
at System.Xml.Linq.XDocument.Load (System.Xml.XmlReader reader, System.Xml.Linq.LoadOptions options) [0x00016] in <89374192b20a41739cf7c5bb822846fe>:0
at System.Xml.Linq.XDocument.Load (System.IO.Stream stream, System.Xml.Linq.LoadOptions options) [0x0000f] in <89374192b20a41739cf7c5bb822846fe>:0
at System.Xml.Linq.XDocument.Load (System.IO.Stream stream) [0x00000] in <89374192b20a41739cf7c5bb822846fe>:0
at VersOne.Epub.Internal.XmlUtils+<>c__DisplayClass0_0.b__0 () [0x00000] in <7c46dbfe3ebf403389304a938822832e>:0
at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in <46c2fa109b574c7ea6739f9fe2350976>:0
at System.Threading.Tasks.Task.Execute () [0x00000] in <46c2fa109b574c7ea6739f9fe2350976>:0
--- 以上为内部抛出异常的堆栈追踪结束 ---
问题复现相关说明
- 当前解析EPUB文件使用的NuGet组件为EpubReader.Cross
- 部分来源的远程EPUB文件可以稳定触发该异常
- 已准备配套的可复现问题的示例工程,用于问题定位与排查
内容的提问来源于stack exchange,提问作者Sreejith Sree

