我发现这段代码将一组人写入XML文件,我想从文件中读取数据并将其打印在控制台中。
static void Main(string[] args)
{
var people = new Person[]
{
new Person{ ID = 1, Name = "Joe", Age = 35, Job = "Manager"},
new Person{ ID = 2, Name = "Jason", Age = 18, Job = "Software Engineer"},
new Person{ ID = 3, Name = "Lisa", Age = 53, Job = "Bakery Owner"},
new Person{ ID = 4, Name = "Mary", Age = 90, Job = "Nurse"},
};
XDocument document = new XDocument
(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("Jason's xml"),
new XElement("People",
from person in people
select new XElement("Person", new XAttribute("ID", person.ID),
new XElement("Name", person.Name),
new XElement("Age", person.Age),
new XElement("Job", person.Job))
)
);
document.Save("People.xml");
var names = from person in XDocument.Load("People.xml").Descendants("People").Elements("Person")
select new Person //line 40
{
ID=Convert.ToInt32(person.Element("ID").Value),
Name=person.Element("Name").Value,
Age = Convert.ToInt32(person.Element("Age").Value),
Job=person.Element("Job").Value
};
foreach (var name in names) //line 48
Console.WriteLine("ID: {0} Name: {1} Age: {2} Job: {3}", name.ID, name.Name, name.Age, name.Job);
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Job { get; set; }
}
}
我收到以下错误:Unhandled exception: System.NullReferenceException: Object reference not set to an instance of an object at line 40 and at System.Linq.EnumerableIterator'2.MoveNext() line 48
。我究竟做错了什么?非常感谢。
答案 0 :(得分:2)
ID
是属性,而不是元素。
person.Element("ID").Value
导致NullReferenceException
。改变它:
person.Attribute("ID").Value
您也可以直接投射XElement
。您不需要使用Value
属性:
var names = from person in XDocument.Load("People.xml").Descendants("People").Elements("Person")
select new Person //line 40
{
ID= (int)person.Attribute("ID"),
Name= (string)person.Element("Name"),
Age = (int)person.Element("Age"),
Job= (string)person.Element("Job")
};