可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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