0

我有这段代码可以将 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

                               };

你知道有什么可以帮助的吗?

4

1 回答 1

0
<?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
于 2013-01-13T19:48:07.830 回答