简体   繁体   中英

Reading XML from isolated storage to ListBox

I have this code to read XML file from isolated storage to 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;
            }
        }

But when I execute it against this 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>

I have this error:

NullReferenceException

In this code fragment:

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

                               };

Do you know what can help?

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

There is no index attribute on your XML, so following line is the reason of you exception:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM