将XML从独立存储读取到ListBox

时间:2013-01-13 19:34:49

标签: c# xml windows-phone-7 isolatedstorage

我有这段代码从隔离存储读取XML文件到ListBox:

using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("People2.xml", FileMode.Open, isoStore))
            {
                XDocument loadedCustomData = XDocument.Load(isoStream);
                var filteredData = from c in loadedCustomData.Descendants("person")
                                   select new Person()
                                   {
                                       Name = c.Attribute("name").Value,
                                       Beneficiary = c.Attribute("beneficiary").Value,
                                       Price = c.Attribute("price").Value,
                                       Deadline = c.Attribute("deadline").Value,
                                       Index = c.Attribute("index").Value,
                                       Description = c.Attribute("description").Value

                                   };

                listBox.ItemsSource = filteredData;
            }
        }

但是当我针对这个XML执行它时

<?xml version="1.0" encoding="utf-8" ?>
<people>
    <person id="2"
            name="przyklad"
            price="850"
            deadline="22.10.12"
            beneficiary="asdasd"
            description="xxx" />
</people>

我有这个错误:

NullReferenceException

在此代码片段中:

select new Person()
                               {
                                   Name = c.Attribute("name").Value,
                                   Beneficiary = c.Attribute("beneficiary").Value,
                                   Price = c.Attribute("price").Value,
                                   Deadline = c.Attribute("deadline").Value,
                                   Index = c.Attribute("index").Value,
                                   Description = c.Attribute("description").Value

                               };

你知道什么可以帮助吗?

1 个答案:

答案 0 :(得分:1)

<?xml version="1.0" encoding="utf-8" ?>
<people>
    <person id="2" name="przyklad" price="850" deadline="22.10.12" beneficiary="asdasd" description="xxx" />
</people>

您的XML上没有index属性,因此以下行是您例外的原因:

Index = c.Attribute("index").Value