简体   繁体   中英

Read from XML using LINQ

I have found this piece of code that writes an array of persons to an XML file and I would like to read the data from the file and print it in the console.

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; }
}

}

I get the following error: 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 . What am I doing wrong? Many thanks.

ID is an attribute, not an element.

person.Element("ID").Value causing the NullReferenceException . Change it like this:

person.Attribute("ID").Value

Also you can cast XElement directly. You don't need to use Value property:

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")
            };

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