利用xmltextreader和xmltextwriter读写xml文件

来源:互联网 发布:河北经济频道网络直播 编辑:程序博客网 时间:2024/06/06 12:24

 

 

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        string xmlpath = Server.MapPath("dc.xml");
        //判断是否存在文件
        FileInfo fileInfo = new FileInfo(xmlpath);
        if (!fileInfo.Exists)
        {
            //一.写xml文件
            // 创建XmlTextWriter类的实例对象

            XmlTextWriter textWriter = new XmlTextWriter(xmlpath, null);
            textWriter.Formatting = Formatting.Indented;

            // 开始写过程,调用WriteStartDocument方法
            textWriter.WriteStartDocument();

            //创建一个节点
            textWriter.WriteStartElement("Root");
            for (int i = 0; i < 8; i++)
            {
                textWriter.WriteStartElement("Record");
                textWriter.WriteElementString("ID", (i + 1).ToString());
                textWriter.WriteElementString("Votes", "0");
                textWriter.WriteEndElement();
            }
            textWriter.WriteEndElement();

            // 写文档结束,调用WriteEndDocument方法
            textWriter.WriteEndDocument();

            // 关闭textWriter
            textWriter.Close();
        }
        else
        {
            //二.读xml文件
            //创建一个XmlTextReader类的对象并调用Read方法来读取XML文件

            XmlTextReader textReader = new XmlTextReader(xmlpath);
            // 节点非空则执行循环体
            while (textReader.Read())
            {
           
                // 读取第一个元素
                if (textReader.LocalName == "ID")
                {
                    textReader.ReadToNextSibling("Votes");
                    Response.Write(textReader.ReadElementContentAsString());
                    Response.Write("<BR>");
                }
            }
       
        }
    }
}