您好我正在尝试将 XML 文件解析为联系人列表,但遇到问题:
public List<ContactModel> GetContacts()
{
var doc = XDocument.Load(HttpContext.Current
.Server
.MapPath(@"..\App_Data\Contacts.xml"));
var result = from items in doc.Descendants("Directory")
select new ContactModel()
{
Id = items.Attribute("ID").Value,
FirstName = items.Attribute("FirstName").Value,
LastName = items.Attribute("LastName").Value,
Telephone = items.Attribute("Telephone").Value,
Email = items.Attribute("Email").Value,
Room = items.Attribute("Room").Value,
Building = items.Attribute("Building").Value,
Location = items.Attribute("Location").Value
};
List<ContactModel> contactList = new List<ContactModel>();
foreach (var item in result)
{
contactList.Add(item);
}
return contactList;
}
尝试循环时出现空异常,我做错了什么?
这是我的 XML
<?xml version="1.0" standalone="yes"?>
<ContactDirectory>
<Directory>
<ID>1</ID>
<FirstName>Peter</FirstName>
<LastName>Sutt</LastName>
<Telephone>777888</Telephone>
<Email>pett@gmail.com</Email>
<Room>3.44</Room>
<Building>Westside</Building>
<Location>Leeds</Location>
</Directory>
<Directory>
<ID>2</ID>
<FirstName>Fred</FirstName>
<LastName>West</LastName>
<Telephone>1234</Telephone>
<Email>fred@west.com</Email>
<Room>1.23</Room>
<Building>Cromwell St</Building>
<Location>Gloster</Location>
</Directory>
<Directory>
</ContactDirectory>