How can I get single node data using linq

后端 未结 5 947
生来不讨喜
生来不讨喜 2021-01-29 09:27

I have the following xml file


  
    1
    Computer
    Infor         


        
5条回答
  •  梦谈多话
    2021-01-29 09:34

    Load it first with XDocument

    XDocument test = XDocument.Load("test.xml");
    

    then,

        var qry = (from item in test.Descendants("category")
          where item.Element("id").Value == 1
          select new
          {
             Name = (string)test.Element("name").Value
             Description = (string)test.Element("description").Value
             Active = (string)test.Element("active").Value
          }).FirstOrDefault();
    

    This created an anonymous type and you can now display your data like this:

    if (qry != null) {
    Console.WriteLine(qry.Name);
    Console.WriteLine(qry.Description);
    Console.WriteLine(qry.Active);
    }
    

提交回复
热议问题