LINQ to XML extract nested elements

前端 未结 2 1874
说谎
说谎 2021-01-29 13:47

I\'m new to LINQ and XML parsing and rather new to C# programming. For the following XML structure, I\'m trying to extract the nested elements:

           


        
相关标签:
2条回答
  • 2021-01-29 14:24

    You can do it this way using linq:

    var result = from p in xmlDoc.Descendants("person")
                 from a in p.Descendants("address")
                 where p.Element("personNumber").Value == "2" 
                 select new 
                     { 
                       City = a.Element("city").Value, 
                       Location = a.Element("location").Value 
                     };
    
    0 讨论(0)
  • 2021-01-29 14:26

    Sth like the following should work:

    XDocument xmlDoc = XDocument.Load(@"mypath\persons.xml");
    
    var q = from e in xmlDoc.Descendants("person")
            where e.Element("personNumber").Value == "2"
            let address = e.Descendants("address")
            from a in address
            select new {
               city = a.Element("city").Value,
               location = a.Element("location").Value
            };
    

    With the sample xml provided in the OP the above linq query produces the following result:

    [0] = { city = "XXX", location = "1" }
    [1] = { city = "YYY", location = "2" }
    
    0 讨论(0)
提交回复
热议问题