文章类型: .NET
关键词: 文件,读写,XML,解析
内容摘要:

文件读写与XML解析

2015/7/29 14:48:09    来源:apple    阅读:

一、如何读写文件

  1、创建一个文件流

  2、创建阅读器或者写入器

  3、执行读写操作

  4、关闭阅读器或者写入器

  5、关闭文件流

示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
 
namespace TextReader
{
    public partial class TextReader : Form
    {
        public TextReader()
        {
            InitializeComponent();
        }
        private void btnWrite_Click(object sender, EventArgs e)
        {
            string path = txtFilePath.Text;
            string content = txtContent.Text;
            if (String.IsNullOrEmpty(path) == true)
            {
                MessageBox.Show("文件路径不能为空");
                return;
            }
            try
            {
                //创建文件流
                FileStream myFs = new FileStream(path, FileMode.CreateNew);
                //创建写入器
                StreamWriter mySw = new StreamWriter(myFs);
                //将录入的内容写入文件
                mySw.Write(content);
                //关闭写入器
                mySw.Close();
                //关闭文件流
                myFs.Close();
 
                ////直接写入方式
                //StreamWriter mySw = new StreamWriter(path);
                //mySw.Write(content);
                //mySw.Close();
 
                MessageBox.Show("写入成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
 
        private void btnRead_Click(object sender, EventArgs e)
        {
            string path = txtFilePath.Text;
            string content;
            if (String.IsNullOrEmpty(path) == true)
            {
                MessageBox.Show("文件路径不能为空");
                return;
            }
            try
            {
                //创建文件流
                FileStream myfs = new FileStream(path, FileMode.Open);
                //创建读取器
                StreamReader mySr = new StreamReader(myfs);
                //读取文件所有内容
                content = mySr.ReadToEnd();
                txtContent.Text = content;
                //关闭读取器
                mySr.Close();
                //关闭文件流
                myfs.Close();
 
                ////直接读取方式
                //StreamReader mySr = new StreamReader(path);
                //content = mySr.ReadToEnd();
                //txtContent.Text = content;
                //mySr.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
    }
}

 

文件流:

          Create用指定的名称新建一个文件

          CreateNew新建一个文件

          Open打开一个文件

          OpenOrCreate如果文件不存在,则用指定的名称新建一个文件并打开它

          FileMode属于枚举型

注意:读取文件数据时,其FileMode应该设置为FileMode.Open

二、File类的方法:

      Existsstring path)用于检查指定文件是否存在,该方法返回一个布尔值

      Copy(string SourceFilePath,string DestinationFilePath)

      Move(string sourceFileName,string destFileName)

      Delete(string path)

三、Directory类的方法:

      Exists(string path)

      Move(string sourceDirName,string destDirName)

      Deletestringbool

四、XML的解析:

                              操作XML的对象属性和方法

  1XmlDocument对象:DocumentElement属性  获取根节点

                                 ChildNodes属性 获取所有子节点

                                 Load()方法 读取整个XML的结构

  2XmlNode对象:InnerText属性  当前节点的值

                            Name属性 当前节点的名字

                            ChildNodes属性 当前节点的所有子节点

示例:   

对于下面的XML文件“temp.rss” ,XML文件的结构如下

<?xml version="1.0" encoding="gb2312"?><rss version="2.0">
<channel>
<title>百度港澳焦点新闻</title>
        <image>
        <title>news.baidu.com</title>
        <link>http://news.baidu.com</link>
        <url>http://img.baidu.com/img/logo-news.gif</url>
        </image>
<description></description>
<link>http://news.baidu.com</link>
<language>zh-cn</language>
<docs></docs>
<generator>www.baidu.com</generator>
<ttl>5</ttl>
<item>
        <title><![CDATA[香港警方:韩国MERS患者2名紧密接触者拒接受隔离]]></title>
        <link><![CDATA[http://news.qtv.com.cn/system/2015/05/30/012428017.shtml]]></link>
        <pubDate><![CDATA[2015-05-30T09:07:03.000Z]]></pubDate>
        <source><![CDATA[青岛网络电视台]]></source>
        <author><![CDATA[青岛网络电视台]]></author>
        <description><![CDATA[
        <a target="_blank" href="http://news.qtv.com.cn/system/2015/05/30/012428017.shtml"><img border="0" src="http://t1.baidu.com/it/u=http%3A%2F%2Fimage.qtv.com.cn%2F0%2F12%2F79%2F91%2F12799104_488636.jpg&fm=30"></a><br>
                16名密切接触者正在麦理浩夫人度假村改造的隔离营接受隔离。   29日晚11时许,10多名医务人员乘车进入麦理浩夫人度假村隔离营,坐在车头人员有人做足装备,戴了口罩、眼罩及穿上保护衣,后面戴口罩者则带备轻便行装。   据香港东网报道,来自韩国的首例中东呼吸综合征疑似病例确诊后,由于该患者...<br />
                                 <a href="http://news.qtv.com.cn/system/2015/05/30/012428017.shtml" target="_blank" style="font-size:13px">香港警方:韩国MERS患者2名紧密接触者拒接受隔离</a><nobr><span style="padding-left:10px;font-size:12px;color:#666666">青岛网络电视台</font></nobr><br>
                                      - <a href="http://news.baidu.com/n?cmd=2&page=http%3A%2F%2Fnews.qtv.com.cn%2Fsystem%2F2015%2F05%2F30%2F012428017.shtml&pn=1&clk=crel&cls=gangaotai&where=focuspage&class=gangaotai"><font color="#008000">1条相关&gt;&gt;</font></a><br>]]></description>
</item>
<item>
        <title><![CDATA[香港旅发局夏季八千万港元宣传 冀吸引过夜旅客刺..]]></title>
        <link><![CDATA[http://www.chinanews.com/ga/2015/05-29/7310739.shtml]]></link>
        <pubDate><![CDATA[2015-05-30T09:07:03.000Z]]></pubDate>
        <source><![CDATA[中国新闻网]]></source>
        <author><![CDATA[中国新闻网]]></author>
        <description><![CDATA[
                中新社香港5月29日电 (记者 李焯龙)香港旅游发展局(旅发局)29日公布,下月中起举办近年最大规模的推广计划,在内地各重点市场展开推广工作,幷联同业界推出多款旅游产品、酒店住宿优惠、大抽奖,冀吸引更多过夜旅客今年夏季来香港,刺激消费市道。   当天,旅发局介绍这项题为“香港FUN享夏日...<br />
                                 - <a href="http://www.chinanews.com/ga/2015/05-29/7310739.shtml" target="_blank"><font color="#008000">中国新闻网</font></a> 
                                         - <a href="http://www.chinanews.com/ga/2015/05-29/7310258.shtml" target="_blank"><font color="#008000">中国新闻网</font></a> 
                                         - <a href="http://www.chinanews.com/ga/2015/05-29/7309442.shtml" target="_blank"><font color="#008000">中国新闻网</font></a> 
                                      - <a href="http://news.baidu.com/n?cmd=2&page=http%3A%2F%2Fwww.chinanews.com%2Fga%2F2015%2F05-29%2F7310739.shtml&pn=1&clk=crel&cls=gangaotai&where=focuspage&class=gangaotai"><font color="#008000">23条相关&gt;&gt;</font></a><br>]]></description>
</item>
<item>
        <title><![CDATA[香港六月初开拍清宫旧藏、海外私藏系列中国艺术品 ]]></title>
        <link><![CDATA[http://www.chinanews.com/ga/2015/05-29/7310646.shtml]]></link>
        <pubDate><![CDATA[2015-05-30T09:07:03.000Z]]></pubDate>
        <source><![CDATA[中国新闻网]]></source>
        <author><![CDATA[中国新闻网]]></author>
        <description><![CDATA[
                中新社香港5月29日电 (记者 孙自法)知名拍卖行香港苏富比将于6月1日至2日举行一系列中国艺术品拍卖,拍品包括清宫旧藏乾隆御制鼻烟壶、比利时私人珍藏中国艺术品、第二代香港家族珍藏玉器及艺术品等共622件,总估价超过5700万港元。   据介绍,系列中国艺术品拍卖分为3场,“鼻烟壶珍藏”...<br />
                                 - <a href="http://www.chinadaily.com.cn/hqcj/xfly/2015-05-30/content_13772497.html" target="_blank"><font color="#008000">中国日报网</font></a> 
                                         - <a href="http://www.chinanews.com/ga/2015/05-29/7310646.shtml" target="_blank"><font color="#008000">中国新闻网</font></a> 
                                      - <a href="http://news.baidu.com/n?cmd=2&page=http%3A%2F%2Fwww.chinanews.com%2Fga%2F2015%2F05-29%2F7310646.shtml&pn=1&clk=crel&cls=gangaotai&where=focuspage&class=gangaotai"><font color="#008000">11条相关&gt;&gt;</font></a><br>]]></description>
</item>
<item>
        <title><![CDATA[中国首家电视媒体——香港“亚洲电视”成立,初..]]></title>
        <link><![CDATA[http://www.chinadadian.gov.cn/news_view.asp?id=6785]]></link>
        <pubDate><![CDATA[2015-05-30T09:07:03.000Z]]></pubDate>
        <source><![CDATA[中国大典编修指导委员会]]></source>
        <author><![CDATA[中国大典编修指导委员会]]></author>
        <description><![CDATA[
                1958年5月29日,中国首家电视媒体——香港“亚洲电视”成立,初名“丽的映声”。<br />
                                 - <a href="http://www.chinadadian.gov.cn/news_view.asp?id=6785" target="_blank"><font color="#008000">中国大典编修指导委员会</font></a> 
                                      - <a href="http://news.baidu.com/n?cmd=2&page=http%3A%2F%2Fwww.chinadadian.gov.cn%2Fnews_view.asp%3Fid%3D6785&pn=1&clk=crel&cls=gangaotai&where=focuspage&class=gangaotai"><font color="#008000">1条相关&gt;&gt;</font></a><br>]]></description>
</item>
</channel>
</rss>

 

代码的解析过程如下:

/// <summary>
/// 获取RSS文件中的文章列表
/// </summary>
/// <returns></returns>
public override bool FetchArticles()
{
    string filePath = "temp.rss";
 
    try
    {
        if (this.articles == null)
            this.articles = new Dictionary<string, Article>();
 
        this.articles.Clear();
 
        WebClient myClient = new WebClient();
        myClient.DownloadFile(Url, filePath);
 
        XmlDocument myXml = new XmlDocument();
        myXml.Load(filePath);
 
        //定位channel 节点
        XmlNode channel = myXml.DocumentElement.FirstChild; //channel node
 
        //定位item 节点
        foreach (XmlNode node in channel.ChildNodes)
        {
            if (node.Name == "item")
            {
                Article atcl = new Article();
 
                foreach (XmlNode subNode in node.ChildNodes)
                {
                    switch (subNode.Name)
                    {
                        case "title":
                            atcl.Title = subNode.InnerText;
                            break;
                        case "link":
                            atcl.Url = subNode.InnerText;
                            break;
                    }
                }
                this.articles.Add(atcl.Title, atcl);
            }
        }
 
        Clicks++;
        return true;
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
        return false;
    }
}

 

↑ 上一篇文章:浅淡反射问题 关键词:C#,Reflection,convert,string.. 发布日期:2015/7/29 14:47:07
↓ 下一篇文章:余光中《乡愁》赏析 关键词:台湾,余光中,乡愁 发布日期:2015/7/29 14:49:23
相关文章:
面向对象C# OOP编程复习 关键词:泛型集合,构造函数,子类构造函数,函数重载,多态,父类类型作为参数,设计模式,XML文件解析,动.. 发布日期:2015-07-25 17:40
VC++ MSXML创建XML文件以及对XML文档解析 关键词:VC++,MSXML创建XML文件以及对XML文档解析 发布日期:2016-08-23 09:41
C# 读写App.config配置文件的方法 关键词:C#,读写,App.config,配置文件,方法 发布日期:2018-08-20 09:56
相关目录:.NET软件开发ANDROID
我要评论
正在加载评论信息......