get XML Namespace Elements with C#

前端 未结 2 1343
清酒与你
清酒与你 2021-01-26 22:58

I having a bit of trouble parsing an xml file with a namespace
XML Format


<         


        
2条回答
  •  借酒劲吻你
    2021-01-26 23:16

    You can use Linq-to-XML and Linq itself

     XDocument doc = XDocument.Load(@"file.xml");
     XNamespace ns="http://rss.flightstats.com/ns/rss/1.0";
    
     var flight = doc.Descendants(ns + "FlightHistory");
     foreach (var ele in flight)
     {
      Console.WriteLine(ele.Attribute("FlightHistoryId").Value);
      }
    

    OR

      var flight = doc.Descendants(ns + "FlightHistory")
                      .Select(ele => new 
                       {
                           FlightHistoryId=ele.Attribute("FlightHistoryId").Value,
                           DepartureDate=ele.Attribute("DepartureDate").Value,
                           ArrivalDate=ele.Attribute("ArrivalDate").Value 
                       }).FirstOrDefault();
        if (flight != null)
        {
            Console.WriteLine(flight.FlightHistoryId + " " + flight.DepartureDate + " " + flight.ArrivalDate);
        }
    

提交回复
热议问题