asp.net环境下处理xml排序

来源:互联网 发布:淘宝网电脑客户端 编辑:程序博客网 时间:2024/05/16 02:14

//index.aspx: 显示xml文件内容,以及添加,删除,修改

using System;
using System.Data;
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 LTP.Accounts.Bus;
using System.Xml;
using System.Text;
using System.Xml.XPath;
using System.IO;
using System.Text.RegularExpressions;

public partial class Home_Pic_index : PageBase
{

    //int PermId_Add = 45;//增加产品权限
    //int PermId_Search = 47;//查询产品权限
    //int PermId_Modify = 48;//修改产品权限
    //int PermId_Delete = 49;//删除产品权限


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //初始化插入位置
            string file = Server.MapPath(ConfigurationManager.AppSettings["XmlFile"]);
            XmlDocument doc = new XmlDocument();
            doc.Load(file);

            XmlElement root = doc.DocumentElement;
            //此时设置的count+1,是为了直接点击提交时,数据添加到xml文件的节点末尾
            int count = root.ChildNodes.Count + 1;
            txtPos.Text = count.ToString();
            DataBind1();
        }
    }

    #region 添加 BtnAdd_Click
    /// <summary>
    /// 添加新节点
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnAdd_Click(object sender, EventArgs e)
    {
        string strPicName = "";
        //图片处理
        LJH.Common.UploadFile uploadfile = new LJH.Common.UploadFile();
        //设置上传文件的目标地址
        uploadfile.UpFilePath = Server.MapPath("~/pic");
        //设置服务端文件的虚拟路径
        uploadfile.PicUrl = "pic/";
        //如果上传图片为空,则EZ_PicPath字段的内容不变
        if (String.IsNullOrEmpty(uploadModify.PostedFile.FileName))
        {
            return;
        }
        if (!Regex.IsMatch(uploadModify.PostedFile.FileName, ".+[.]{1}jpg|.+[.]{1}gif|.+[.]{1}png"))
        {
            LJH.Common.MessageBox.Show(this, "请输入图片,格式为 *.jpg !");
            return;
        }
        strPicName = uploadfile.fileSaveAs(uploadModify.PostedFile);
        try
        {
            WriteXmlData(strPicName, Convert.ToInt32(txtPos.Text));
            LJH.Common.MessageBox.Show(this, "添加成功!");
        }
        catch
        {
            LJH.Common.MessageBox.Show(this, "添加失败!");
        }
        DataBind1();
    }
    #endregion

    #region gridView事件


    /// <summary>
    /// 删除数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
        //加载xml文件
        string file = Server.MapPath(ConfigurationManager.AppSettings["XmlFile"]);//("~/homepic/bcastr.xml");
        XmlDocument doc = new XmlDocument();
        doc.Load(file);
        XmlNode node = doc.SelectSingleNode(String.Format("/bcaster/item[@orderid={0}]", Id));
        try
        {
            node.ParentNode.RemoveChild(node);
            //保存数据
            using (XmlTextWriter writer = new XmlTextWriter(file, Encoding.UTF8))
            {
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 2; writer.IndentChar = ' ';
                //doc.WriteTo(writer);
                doc.WriteContentTo(writer);
            }
            txtPos.Text = Convert.ToString(doc.DocumentElement.ChildNodes.Count + 1);
            //设置排序号顺序
            SetNodeidSequence();
            LJH.Common.MessageBox.Show(this, "删除成功!");
        }
        catch
        {
            LJH.Common.MessageBox.Show(this, "删除失败!");

        }

        DataBind1();
    }
    /// <summary>
    /// 设置xml文件中的节点有序
    /// </summary>
    protected void SetNodeidSequence()
    {
        string file = Server.MapPath(ConfigurationManager.AppSettings["XmlFile"]);//("~/homepic/bcastr.xml");
        XmlDocument doc = new XmlDocument();
        doc.Load(file);
        XmlElement root = doc.DocumentElement;
        int index = 0;
        int count = root.ChildNodes.Count;
        while (index < count)
        {
            root.ChildNodes[index].Attributes["orderid"].Value = Convert.ToString(++index);
        }
        //保存数据
        using (XmlTextWriter writer = new XmlTextWriter(file, Encoding.UTF8))
        {
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 2; writer.IndentChar = ' ';
            //doc.WriteTo(writer);
            doc.WriteContentTo(writer);
        }
    }
    #endregion
    /// <summary>
    /// 读取xml文件,并将数据绑定到GridView控件
    /// </summary>
    protected void DataBind1()
    {
        string file = Server.MapPath(ConfigurationManager.AppSettings["XmlFile"]);
        XmlTextReader reader = new XmlTextReader(file);
        DataTable dt = new DataTable("bcaster");
        dt.Columns.Add(new DataColumn("item_url", typeof(string)));
        dt.Columns.Add(new DataColumn("link", typeof(string)));
        dt.Columns.Add(new DataColumn("orderid", typeof(string)));
        reader.ReadStartElement();// MoveToElement();
        while (reader.Read())
        {
            DataRow dr = dt.NewRow();
            if (reader.HasAttributes)
            {
                reader.MoveToFirstAttribute();
                for (int i = 0; i < reader.AttributeCount; i++)
                {
                    dr[reader.Name] = reader.Value;
                    reader.MoveToNextAttribute();
                }
                dt.Rows.Add(dr);
            }
        }
        reader.Close();
        //DataView dv = dt.DefaultView;
        //dv.Sort = "orderid asc";
        //GridView1.DataSource = dv;
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    /// <summary>
    /// 将文件名称写入xml文件
    /// </summary>
    /// <param name="filename">待写入xml文件的文件名称,即上传的文件</param>
    /// <param name="index">将filename文件名称插入到index节点之前</param>
    protected void WriteXmlData(string filename, int index)
    {
        //加载xml文件
        try
        {
            string file = Server.MapPath(ConfigurationManager.AppSettings["XmlFile"]);
            XmlDocument doc = new XmlDocument();
            doc.Load(file);

            XmlElement root = doc.DocumentElement;
            int count = root.ChildNodes.Count;
            //创建新节点
            XmlNode node = doc.CreateNode("element", "item", "");
            //创建节点属性
            XmlAttribute attr = doc.CreateAttribute("item_url");
            attr.Value = filename;
            node.Attributes.Append(attr);
            //attr = doc.CreateAttribute("link");
            //attr.Value = "#";
            //node.Attributes.Append(attr);
            attr = doc.CreateAttribute("orderid");
            attr.Value = Convert.ToString(count + 1);
            node.Attributes.Append(attr);
            if (index <= count)
            {
                //将新增的节点插入到指定的位置
                XmlNode current = root.ChildNodes[index - 1];
                current.ParentNode.InsertBefore(node, current);
            }
            else
            {
                //添加到节点集的末尾
                root.AppendChild(node);
            }
            //保存数据
            using (XmlTextWriter writer = new XmlTextWriter(file, Encoding.UTF8))
            {
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 2; writer.IndentChar = ' ';
                //doc.WriteTo(writer);
                doc.WriteContentTo(writer);
            }
            //重置插入位置
            txtPos.Text = Convert.ToString(doc.DocumentElement.ChildNodes.Count + 1);
            //设置排序号顺序
            SetNodeidSequence();
        }
        catch (Exception ex)
        {
            LJH.Common.MessageBox.Show(this, String.Format("处理失败! 原因: {0}", ex.Message));
        }

    }
    /// <summary>
    /// //根据orderid属性,对节点排序
    /// </summary>
    private void SortXml()
    {
        try
        {
            //生成新的文件bcastr1.xml
            string file2 = Server.MapPath(ConfigurationManager.AppSettings["XmlFile"]);
            file2 = file2.Insert(file2.Length - 4, "1");
            string file1 = Server.MapPath(ConfigurationManager.AppSettings["XmlFile"]);
            using (XmlTextWriter writer = new XmlTextWriter(file2, Encoding.UTF8))
            {
                writer.WriteStartDocument();
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 2;
                writer.IndentChar = ' ';
                writer.WriteComment("参数设置: 自动播放时间(秒)|文字颜色|文字背景色|文字背景透明度|按键数字颜色|当前按键颜色|普通按键色彩");
                writer.WriteStartElement("bcaster");
                writer.WriteAttributeString("config", "2|0xffffff|0x000000|80|0xffffff|0x0099ff|0x000000");
                //排序
                string xpath = "/bcaster/item";
                XPathDocument doc = new XPathDocument(file1);
                XPathNavigator nav = doc.CreateNavigator();
                XPathExpression exp = nav.Compile(xpath);
                exp.AddSort("@orderid", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number);
                XPathNodeIterator nodeIter2 = nav.Select(exp);
                //输入节点到writer
                while (nodeIter2.MoveNext())
                {
                    writer.WriteNode(nodeIter2.Current, false);
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
            }

            File.Delete(file1);
            File.Move(file2, file1);
            LJH.Common.MessageBox.Show(this, "排序完成!");
        }
        catch
        {
            LJH.Common.MessageBox.Show(this, "排序失败!");

        }
    }
    protected void btnSort_Click(object sender, EventArgs e)
    {
        //根据orderid属性,对节点排序
        SortXml();
        //设置排序号顺序
        SetNodeidSequence();
        //重新绑定数据
        DataBind1();
    }
    protected void txtPos_TextChanged(object sender, EventArgs e)
    {
        int result = 0;
        if (!Int32.TryParse(this.txtPos.Text, out result))
        {

            this.txtPos.Text = "";
            LJH.Common.MessageBox.Show(this, "输入的必须是数字!");
        }
        else if (result <= 0)
        {
            this.txtPos.Text = "";
            LJH.Common.MessageBox.Show(this, "输入的数字必须大于零!");
        }
    }
}

 

//operation.aspx  负责替换xml中的指定节点

using System;
using System.Data;
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.Text;
using System.Text.RegularExpressions;
using System.IO;

public partial class Manage_Case_operation : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //加载xml文件
            string file = Server.MapPath(ConfigurationManager.AppSettings["XmlFile"]);
            XmlDocument doc = new XmlDocument();
            doc.Load(file);

            XmlNode oldnode = doc.SelectSingleNode(String.Format("/bcaster/item[@orderid={0}]", Request.Params["id"]));
            ViewState["ImageUrl"] = "~/" + oldnode.Attributes["item_url"].Value;
        }
        this.img1.ImageUrl = ViewState["ImageUrl"].ToString();
    }
    protected void btnOperation_Click(object sender, EventArgs e)
    {
        string strPicName = "";
        //图片处理
        LJH.Common.UploadFile uploadfile = new LJH.Common.UploadFile();
        //设置上传文件的目标地址
        uploadfile.UpFilePath = Server.MapPath("~/pic");
        //设置服务端文件的虚拟路径
        uploadfile.PicUrl = "pic/";
        //如果上传图片为空,则EZ_PicPath字段的内容不变
        if (String.IsNullOrEmpty(uploadModify.PostedFile.FileName))
        {

            LJH.Common.MessageBox.Show(this, "请选择上传文件!");
            return;
        }
        if (!Regex.IsMatch(uploadModify.PostedFile.FileName, ".+[.]{1}jpg|.+[.]{1}gif|.+[.]{1}png"))
        {
            LJH.Common.MessageBox.Show(this, "请输入图片,格式为 *.jpg !");
            return;
        }
        strPicName = uploadfile.fileSaveAs(uploadModify.PostedFile);

        //加载xml文件
        string file = Server.MapPath(ConfigurationManager.AppSettings["XmlFile"]);
        XmlDocument doc = new XmlDocument();
        doc.Load(file);

        XmlNode oldnode = doc.SelectSingleNode(String.Format("/bcaster/item[@orderid={0}]", Request.Params["id"]));
        String strOldPic = Server.MapPath("~/" + oldnode.Attributes["item_url"].Value);
        XmlElement newnode = doc.CreateElement("item");
        //创建节点属性
        XmlAttribute attr = doc.CreateAttribute("item_url");
        attr.Value = strPicName;
        newnode.Attributes.Append(attr);
        //attr = doc.CreateAttribute("link");
        //attr.Value = "#";
        //newnode.Attributes.Append(attr);
        attr = doc.CreateAttribute("orderid");
        attr.Value = Request.Params["id"].ToString();
        newnode.Attributes.Append(attr);
        //节点替换
        oldnode.ParentNode.ReplaceChild(newnode, oldnode);
        //保存数据
        try
        {
            using (XmlTextWriter writer = new XmlTextWriter(file, Encoding.UTF8))
            {
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 2;
                writer.IndentChar = ' ';
                doc.WriteTo(writer);
            }
            ViewState["ImageUrl"] = "~/" + strPicName;
            File.Delete(strOldPic);
            LJH.Common.MessageBox.Show(this, "修改成功!");
            Response.Redirect("operation.aspx?id=" + Request.Params["id"].ToString());
        }
        catch
        {
            LJH.Common.MessageBox.Show(this, "修改失败!");

        }
    }
}

原创粉丝点击