使用C#获取XML属性 [英] Get XML attribute with C#

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

问题描述

我有一个类似以下的XML文件.

I have an XML file like the following.

<div class="time">
   <span class="title">Bla: </span>
   <span class="value">Thu 20 Jan 11</span>
</div>

如何使用C#获取值"11月20日星期四"? 预先感谢

How can I get value "Thu 20 Jan 11" with C#? thanks in advance

推荐答案

鉴于您确实有一个XML文件,那么您需要将该文件加载到XmlDocument中并使用XPath查找所需内容:

Given that you do have an XML file like you say, then you need could load the file into an XmlDocument and find what you want using XPath:

class Program
    {
        static void Main(string[] args)
        {
            var xml = "<div class=\"time\">" +
                        "<span class=\"title\">Bla: </span>" +
                        "<span class=\"value\">Thu 20 Jan 11</span>" +
                        "</div>";
            var document = new XmlDocument();

            try
            {
                document.LoadXml(xml);
            }
            catch (XmlException xe)
            {
                // Handle and/or re-throw
                throw;
            }

            var date = document.SelectSingleNode("//span[@class = 'value']").InnerText;

            Console.WriteLine(date);

            Console.ReadKey();
        }
    }

输出:2011年1月20日星期四

Output: Thu 20 Jan 11

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

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