get XML Namespace Elements with C#

前端 未结 2 1342
清酒与你
清酒与你 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);
        }
    
    0 讨论(0)
  • 2021-01-26 23:30

    Here's one in Regular expression

    string xmlFileString="<rss version.....</item></channel>";
    
    Regex r=new Regex("(?<=<fh:FlightHistory).*?(?=>|</fh:FlightHistory>)",RegexOptions.Singleline);
    
    foreach(Match m in r.Matches(xmlFileString))
    Console.WriteLine(m.Value);//your required output
    
    0 讨论(0)
提交回复
热议问题