使用 C# 获取 XML 命名空间元素 [英] get XML Namespace Elements with C#

查看:24
本文介绍了使用 C# 获取 XML 命名空间元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在解析带有命名空间的 xml 文件时遇到了一些麻烦
XML 格式

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>

我想用 C# 读取 fh:FlightHistory 属性,但我没有找到任何解决方案.

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

提前致谢

推荐答案

您可以使用 Linq-to-XMLLinq 本身

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

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

这篇关于使用 C# 获取 XML 命名空间元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆