`
webcode
  • 浏览: 5945786 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

asp.net环境下处理xml排序

 
阅读更多

//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, "修改失败!");

}
}
}

分享到:
评论

相关推荐

    .net web的xml增删改排序操作。

    asp.net web的xml增删改排序操作。

    ASP.NET常见问题集锦.zip

    关于ASP.Net中的时间处理.txt 关于上下文.doc 创建可分页、可排序的 DataGrid.doc 创建用于 ASP.NET 的分页程序控件.doc 创建用于ASP.NET的分页控件.txt 利用 ASP.NET 创建多页自定义报表.doc 利用属性扩展元...

    ASP.NET学习大全

    ASP.NET学习大全,包括以下文档: GridView导出excel 小山的TreeView数据绑定方法 ADO.NET在开发中的部分使用方法和技巧.txt ADO.NET中的视图和过滤器.doc ...在ASP.NET中使用Treeview控件和XML.txt

    asp.net学习大全(超全面的资料整合)

    包含内容部分示例: GridView导出excel 小山的TreeView数据绑定方法 ADO.NET在开发中的部分使用方法和技巧.txt ADO.NET中的视图和过滤器.doc ASP .NET - ArrayList对象.txt ...在ASP.NET中使用Treeview控件和XML.txt

    asp.net知识库

    在ASP.NET页面中推荐使用覆写(Override)而不是事件处理(Event Handler) 常用编码工具类,支持base64,md5,des,crc32 也谈谈技术面试 在C#里把ArrayList转换为Array 或 把Array转换为ArrayList C# 2.0 在.NET 2.0中...

    GridView无刷新排序(Ajax+ASP.NET+XML)

    GridView无刷新排序(Ajax+ASP.NET+XML)! 很值得下载看看!资源免费,大家分享!!

    ASP.NET 控件的使用

    第一部分 构建ASP.NET页面 第1章 ASP.NET Framework概览 2 1.1 ASP.NET和.NET Framework 5 1.1.1 框架类库 5 1.1.2 公共语言运行库 9 1.2 ASP.NET控件 10 1.2.1 ASP.NET控件概览 11 1.2.2 HTML控件 12 1.2.3 理解...

    asp.net技术内幕(1)

    1.2.1 简单的ASP.NET页面 1.2.2 ASP.NET控件的优点 1.2.3 ASP.NET控件概述 1.3 向ASP.NET页面中添加应用逻辑 1.3.1 处理控件事件 1.3.2 处理页面事件 1.4 ASP.NET页面的结构 1.4.1 ...

    ASP.NET.4揭秘

    asp.net 4揭秘.第1卷》 第一部分 构建asp.net页面 第1章 asp.net framework概览2 1.1 asp.net和.net framework5 1.1.1 框架类库5 1.1.2 公共语言运行库10 1.2 asp.net控件11 1.2.1 asp.net控件概览11 1.2.2 html控件...

    ASP.NET4高级程序设计第4版 带目录PDF 分卷压缩包 part1

    书中还深入讲述了其他ASP.NET图书遗漏的高级主题,如自定义控件的创建、图像处理、加密等。此外,《ASP.NET 4高级程序设计(第4版)》专门提供了两章的内容来教你如何用Ajax 技术制作快速响应的页面,以及如何使用微软...

    2.ASP.NET.2.0.高级编程(第4版) [1/7]

    书中提供了大量的实例,可帮助读者快速掌握如何在.NET平台下开发功能强大的ASP.NET应用程序。本书适合有一些基础的ASP.NET初级程序员以及准备迁移到ASP.NET 2.0的编程老手。该书与《ASP.NET 2.0入门经典(第4版)》...

    ASP.NET4高级程序设计(第4版) 3/3

    书中还深入讲述了其他ASP.NET图书遗漏的高级主题,如自定义控件的创建、图像处理、加密等。此外,《ASP.NET 4高级程序设计(第4版)》专门提供了两章的内容来教你如何用Ajax 技术制作快速响应的页面,以及如何使用微软...

    中美 IT 培训 C# Asp.net 全套笔记1

    精通C#.Net、ASP.Net、ADO.Net、AJAX、WEB2.0、XML、JavaScript、SQL Server 2000、Web Service、WSE2.0、.Net Remoting、MultiThread Programming、Socket Programming、Windows Service、Data Structure、 ...

    asp.net专家疑难解答200问

    如何将XML作为数据源绑定到控件 第8章 数据库设计 143.ASP.NET应用程序如何实现与SQL Server数据库的连接 144.ASP.NET应用程序如何实现与ACCESS数据库的连接 146.如何使用ADO.NET在数据库执行SQL...

    中美 IT 培训 C# Asp.net 笔记3

    精通C#.Net、ASP.Net、ADO.Net、AJAX、WEB2.0、XML、JavaScript、SQL Server 2000、Web Service、WSE2.0、.Net Remoting、MultiThread Programming、Socket Programming、Windows Service、Data Structure、 ...

    中美 IT 培训 C# Asp.net 笔记2

    精通C#.Net、ASP.Net、ADO.Net、AJAX、WEB2.0、XML、JavaScript、SQL Server 2000、Web Service、WSE2.0、.Net Remoting、MultiThread Programming、Socket Programming、Windows Service、Data Structure、 ...

    ASP.NET 3.5 开发大全

    第14章 ASP.NET XML和Web Service 14.1 XML简介 14.2 读写XML 14.2.1 XML与HTML 14.2.2 创建XML文档 14.2.3 XML控件 14.2.4 XML文件读取类(XmlTextReader) 14.2.5 XML文件编写类(XmlTextWriter) 14.2.6 XML文本...

    ASP.NET3.5从入门到精通

    第 14 章 ASP.NET XML 和Web Service 14.1 XML 简介 14.2 读写XML 14.2.1 XML 与HTML 14.2.2 创建XML 文档 14.2.3 XML 控件 14.2.4 XML 文件读取类(XmlTextReader) 14.2.5 XML 文件编写类(XmlTextWriter) 14.2.6...

    ASP.NET 3.5 开发大全word课件

    第14章 ASP.NET XML和Web Service 14.1 XML简介 14.2 读写XML 14.2.1 XML与HTML 14.2.2 创建XML文档 14.2.3 XML控件 14.2.4 XML文件读取类(XmlTextReader) 14.2.5 XML文件编写类(XmlTextWriter) 14.2.6 XML文本...

Global site tag (gtag.js) - Google Analytics