get XML Namespace Elements with C#

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

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

<rss version="2.0" xmlns:fh="http://rss.flightstats.com/ns/rss/1.0"> <channel>   <item>     <fh:FlightHistory FlightHistoryId="271955988" DepartureDate="2012-08-16 00:30" ArrivalDate="2012-08-16 04:09"      </fh:FlightHistory>   </item> </channel> 

I want to read fh:FlightHistory attributes with C# , but I didn't find any solution .

Thanks in advance

回答1:

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);     } 


回答2:

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 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!