如何将StreamReader转换为XDocument?

til*_*lak 2 xml isolatedstorage linq-to-xml streamreader windows-phone-7

我在IsolatedStorage中存储XML数据,同时从IsolatedStorage读取数据.我需要将StreamReader转换为XDocument.以下代码我已经习惯将StreamReader转换为XDocument.我收到一个错误:"root element is missing"

using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {                   
                IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("AllHeadLine.xml", FileMode.Open);
                using (StreamReader reader = new StreamReader(isoFileStream))
                {                        
                    displayXmlData.Text = reader.ReadToEnd();                       
                    XDocument offlineHeadline = XDocument.Load(reader);

                }
            }
Run Code Online (Sandbox Code Playgroud)

编辑:XML内容

<category><catname>?????</catname><img>http://www.udayavani.com/udayavani_cms/gall_content/2013/3/2013_3$thumbimg113_Mar_2013_235853890.jpg</img><heading>???? ??? ????? ?????? ???</heading><navigateurl>some Url </navigateurl></category>
Run Code Online (Sandbox Code Playgroud)

怎么解决这个?

Jon*_*eet 9

看看你在做什么:

using (StreamReader reader = new StreamReader(isoFileStream))
{                        
    displayXmlData.Text = reader.ReadToEnd();                       
    XDocument offlineHeadline = XDocument.Load(reader);
}
Run Code Online (Sandbox Code Playgroud)

您正在读取StreamReader通道中的所有数据ReadToEnd,然后您正在尝试将其加载到XDocument.没有更多的数据可供阅读!一些选择:

  • 将其读取为字符串,然后使用该字符串设置displayXmlData.Text 解析文档XDocument.Parse.(如果WP7不支持,请使用StringReaderXDocument.Load
  • ReadToEnd完全摆脱这个电话,没有设置就能过日子displayXmlData.Text.目前尚不清楚这是否是必需的或仅用于诊断目的.

除非你真的需要逐字文本,否则我实际上会避免创建它StreamReader,并直接从中加载Stream.这将让LINQ to XML也进行编码检测.

using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{                   
    using (var stream = storage.OpenFile("AllHeadLine.xml", FileMode.Open))
    {
        XDocument offlineHeadline = XDocument.Load(stream);
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)