繁体   English   中英

使用LINQ从XML读取

[英]Read from XML using LINQ

我发现这段代码将一个人数组写入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 我究竟做错了什么? 非常感谢。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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