How can I get single node data using linq

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

I have the following xml file


  
    1
    Computer
    Infor         


        
相关标签:
5条回答
  • 2021-01-29 09:33

    You can use LINQ to XML like

    XDocument xDoc = XDocument.Load("test.XML");
    var item = xDoc.Descendants("category")
                   .FirstOrDefault(r => r.Element("id").Value == "1");
    if(item == null)
       return;
    
    string Name = item.Element("name").Value;
    string Decription = item.Element("description").Value;
    string active = item.Element("active").Value;
    

    You can assign the results to your TextBoxes as per your requirement.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2021-01-29 09:48
    var xml = XDocument.Parse(xmlDataString);
    
    var categoryElement = xml.Root
        .Elements("category")
        .FirstOrDefault(e => (string)e.Element("id") == "1");
    
    0 讨论(0)
  • 2021-01-29 09:58

    Simply deserialize given XML in object and apply LINQ to Objects. MSDN

    0 讨论(0)
  • 2021-01-29 09:59

    How about using Linq To Xml and converting the elements to a Dictionary<string,string>?

    var xDoc = XDocument.Parse(xml);
    int id=1;
    
    var dict = xDoc.XPathSelectElement("//category[id=" + id + "]")
                .Elements()
                .ToDictionary(e=>e.Name.LocalName , e=>(string)e);
    
    Console.WriteLine(dict["description"]);
    
    0 讨论(0)
提交回复
热议问题