如何从wp8中隔离获取xml文件

时间:2014-03-14 06:17:19

标签: c# .net xml windows-phone-8

我尝试获取Xml文件并将其绑定到列表中 这是我的Xml文件

- <data>
  - <Bookmarkdata>
      <Bookname>TheNfame</Bookname> 
      <Bookid>5a1df538-6e91-4a39-819d-e043c9881fb7</Bookid> 
      <Pageno>0</Pageno> 
    </Bookmarkdata>
  - <Bookmarkdata>
      <Bookname>TheNfame</Bookname> 
      <Bookid>5a1df538-6e91-4a39-819d-e043c9881fb7</Bookid> 
      <Pageno>1</Pageno> 
    </Bookmarkdata>
 </data>

这是我的代码

private void GetBookMarkData()     {

    var doc = new XDocument();
    XDocument xdoc=  new XDocument();
    using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        try
        {
            if (store.FileExists("BookmarkFile.xml"))
            {
                using (var sr = new StreamReader(new IsolatedStorageFileStream("BookmarkFile.xml", FileMode.OpenOrCreate, store)))
                {
                    doc = XDocument.Load(sr);
                   // xdoc = XDocument.Load(sr);
                    var data = from query in doc.Descendants("data")
                               select new Bookmarkdata
                               {
                                   Bookname = (string)query.Element("Bookname"),
                                   Bookid = (string)query.Element("Bookid"),
                                   BookPath = (string)query.Element("BookPath"),
                                   Pageno = (int)query.Element("Pageno")
                               };
                    Bookmark_List.ItemsSource = data;

                }
            }
        }
        catch
            (Exception ex) { }
    }

但是在Catch中返回错误 值不能为空。

参数名称:element

在我的代码中 doc = XDocument.Load(sr); 我有一个xml数据dubag时间,但在下一行是错误请帮助

1 个答案:

答案 0 :(得分:3)

你的LINQ-to-XML查询有点过时了。 query变量代表<data>元素:

var data = from query in doc.Descendants("data")
                               select new Bookmarkdata
                               {
                                   Bookname = (string)query.Element("Bookname"),
                                   Bookid = (string)query.Element("Bookid"),
                                   BookPath = (string)query.Element("BookPath"),
                                   Pageno = (int)query.Element("Pageno")
                               };

因此它没有名为Bookname,Bookid,BookPath或Pageno的直接子项。我想你想要从<Bookmarkdata>元素中选择:

var data = from query in doc.Descendants("Bookmarkdata")
                       select new
                       {
                           Bookname = (string)query.Element("Bookname"),
                           Bookid = (string)query.Element("Bookid"),
                           BookPath = (string)query.Element("BookPath"),
                           Pageno = (int)query.Element("Pageno")
                       };