我在解析带有命名空间的 xml 文件时遇到了一些问题
XML格式
<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>
我想用 C# 读取 fh:FlightHistory 属性,但我没有找到任何解决方案。
提前致谢
请您参考如下方法:
您可以使用 Linq-to-XML 和 Linq 本身
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);
}
或
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);
}
