博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【XML】xml封装方法
阅读量:6227 次
发布时间:2019-06-21

本文共 25574 字,大约阅读时间需要 85 分钟。

起兵有因:    

      最近,总是抱着专业书本或者电脑感觉好没意思,那就寻思着弄本书看看,消遣消遣,喝喝茶看看书,咱也文艺一下,可是关键没有合适的书!武侠吧没心看了,玄幻网游吧太扯淡,爱情吧,受不了搞程序的对着电脑不对美女久了就缺爱了。还是找本历史类的吧!对了,《明朝那些事》。看吧,一看不要紧,夜半三经还加倍呢,小伙够努力吧!(白天没时间,大家都理解)。刚看到朱棣“造反”,这事吧,也不懒人家,朱允文要干他,不反就坐牢。反也得有个理由吧,正苦恼,和尚道衍一剂“勤王清君侧”。其这招在汉武帝时就有了!虽然都知道这事怎么回事,但是咱们还是得有个理由,这样安慰安慰自己,也让兄弟们出去砍人时候有话说。扯远了,说说我这怎么回事吧!最近写一个基于xml的课程设计,连学带做终于搞定,但是事后觉得用着不爽,自己就封装一下,也算安慰一下这几天的辛苦!

战前备事:

       公欲谋反,必先准备!故而咱也看看朱棣怎么做的。定下一个决心,老子反了(建立一个项目)。先去召集大家开开动员大会,找一片场地(建立一个web页面文件)。召集部分精英将领开会小会,透透气。 类的代码: 将领(xml预先准备的类)有姓名,年龄,性别(一般都是男的)等(类的属性)。每个将领有哪些特长如善骑射,弓箭,管理等(怎么封装的公共方法) 总结下:一个项目,一个页面(数据操作和显示),一个类(封装属性方法)

public class Book    {        public string id { get; set; }//图书id        public string bookcategory { get; set; }//图书类别        public string image { get; set; }//图书图片        public string title { get; set; }//图书名称        public string author { get; set; }//图书作者        public string publisher { get; set; }//出版社        public string ISBN { get; set; }//图书编号        public Double price { get; set; }//单价        public int num { get; set; }//库存    }

 

一触即发:

     放一个gridview和表格。gridview进行数据显示,表格便于修改

 

 

表格设置

前台完整代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="XML操作.WebForm1" %>        
书名:
作者:
图书编号:
图书类别:
出版社:
出版编号:
价格:
库存:
图片:
View Code

关于类中方法的调用

创建xml两种方法:

方法一:

//方法一:创建xml并保存        public void Create(string xpath)        {            XDocument books = new XDocument(             new XDeclaration("1.0", "utf-8", "yes"),             new XComment("创建一个图书列表的xml"),             new XElement("Booklist",                 new XAttribute("ID", "000001"),                 new XElement("Book",                     new XElement("BookType", "计算机"),                     new XElement("BookName", "算法与数据结构"),                     new XElement("Auth", "严蔚敏 陈文博"),                     new XElement("Publisher", "清华大学出版社"),                     new XElement("Price", "24"),                     new XElement("PubDate", "2002-1-1"),                     new XElement("Quantity", "10")                     )                 )             );            books.Save(xpath);            Console.Write(books);        }
View Code

方法二:

//方法二        public void Create1(string xpath)        {            XmlDocument doc = new XmlDocument();            //创建指令            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);            doc.AppendChild(dec);            //创建注释            XmlComment xcm = doc.CreateComment("这是我建设的一个关于用户的xml文件");            doc.AppendChild(xcm);            //创建根元素(数据库)            XmlElement root = doc.CreateElement("users");            doc.AppendChild(root);            //创建第一元素(表)            XmlElement user = doc.CreateElement("user");            //建立子元素            XmlElement tom = doc.CreateElement("name");            tom.SetAttribute("id", "001");            tom.SetAttribute("sex", "男");            tom.InnerText = "张三";            user.AppendChild(tom);            //建立子元素            XmlElement jion = doc.CreateElement("name");            jion.SetAttribute("id", "002");            jion.SetAttribute("sex", "男");            jion.InnerText = "司马迁";            user.AppendChild(jion);            //建立子元素            XmlElement jon = doc.CreateElement("name");            jon.SetAttribute("id", "003");            jon.SetAttribute("sex", "女");            jon.InnerText = "小丽";            user.AppendChild(jon);            //添加到根元素            root.AppendChild(user);            //保存            doc.Save(xpath);            //打印           Console.Write(doc.OuterXml);        }
View Code

查询:

///         /// 查询信息        ///         /// 
dbs
public List
GetAll() { List
dbs = (from db in doc.Element("books").Elements("book") orderby db.Attribute("id").Value descending select new Book { id = db.Attribute("id").Value.ToString(), bookcategory = db.Attribute("bookcategory").Value.ToString(), image = db.Element("image").Value.ToString(), title = db.Element("title").Value.ToString(), author = db.Element("author").Value.ToString(), publisher = db.Element("publisher").Value.ToString(), ISBN = db.Element("ISBN").Value.ToString(), price = Convert.ToDouble(db.Element("price").Value), num = Convert.ToInt32(db.Element("num").Value) }).ToList(); return dbs; }
View Code

 

修改:

///         /// 修改        ///         /// 
public bool Modify(string id) { //XElement ex = XElement.Load(@"C:\Users\aa\Desktop\BookShop\BookShop\xml\Books.xml"); //var b = (from f in ex.Descendants("book") where (string)f.Attribute("id").Value.ToString()== id select f).Single(); XElement xe = (from db in doc.Element("books").Elements("book") where db.Attribute("id").Value.ToString() == id select db).Single(); try { xe.Attribute("id").SetValue(id); xe.Element("title").SetValue(title); xe.Element("author").SetValue(author); xe.Attribute("bookcategory").SetValue(bookcategory); xe.Element("publisher").SetValue(publisher); xe.Element("ISBN").SetValue(ISBN); xe.Element("price").SetValue(price); xe.Element("num").SetValue(num); xe.Element("image").SetValue(image); return true; } catch { return false; } }
View Code

添加:

///         /// 添加信息        ///         /// 
public bool Add() { try { XElement root = XElement.Load(filePath); XElement xe = new XElement("book", new XAttribute("id", id), new XAttribute("bookcategory", bookcategory), new XElement("image", image), new XElement("title", title), new XElement("author", author), new XElement("publisher", publisher), new XElement("ISBN", ISBN), new XElement("price", price), new XElement("num", num) ); root.Add(xe); root.Save(filePath); return true; } catch { return false; } }
View Code

删除:

///         /// 删        ///         ///         /// 
public bool Remove(string id) { XElement xe = (from db in doc.Element("books").Elements("book") where db.Attribute("id").Value == id select db).Single() as XElement; try { xe.Remove(); doc.Save(filePath); return true; } catch { return false; } }
View Code

完整的cs代码:

using System.Xml.Linq;namespace XML操作{    public class Book    {        public string id { get; set; }//图书id        public string bookcategory { get; set; }//图书类别        public string image { get; set; }//图书图片        public string title { get; set; }//图书名称        public string author { get; set; }//图书作者        public string publisher { get; set; }//出版社        public string ISBN { get; set; }//图书编号        public Double price { get; set; }//单价        public int num { get; set; }//库存                private static XDocument doc = new XDocument();        public static string filePath = @"C:\Users\宁超\Desktop\XML操作\XML操作\xml\Books.xml";        public Book()        {            doc = XDocument.Load(filePath);        }        public Book(string xpath)            : this()        {            filePath = xpath;        }        //方法一:创建xml并保存        public void Create(string xpath)        {            XDocument books = new XDocument(             new XDeclaration("1.0", "utf-8", "yes"),             new XComment("创建一个图书列表的xml"),             new XElement("Booklist",                 new XAttribute("ID", "000001"),                 new XElement("Book",                     new XElement("BookType", "计算机"),                     new XElement("BookName", "算法与数据结构"),                     new XElement("Auth", "严蔚敏 陈文博"),                     new XElement("Publisher", "清华大学出版社"),                     new XElement("Price", "24"),                     new XElement("PubDate", "2002-1-1"),                     new XElement("Quantity", "10")                     )                 )             );            books.Save(xpath);            Console.Write(books);        }        //方法二        public void Create1(string xpath)        {            XmlDocument doc = new XmlDocument();            //创建指令            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);            doc.AppendChild(dec);            //创建注释            XmlComment xcm = doc.CreateComment("这是我建设的一个关于用户的xml文件");            doc.AppendChild(xcm);            //创建根元素(数据库)            XmlElement root = doc.CreateElement("users");            doc.AppendChild(root);            //创建第一元素(表)            XmlElement user = doc.CreateElement("user");            //建立子元素            XmlElement tom = doc.CreateElement("name");            tom.SetAttribute("id", "001");            tom.SetAttribute("sex", "男");            tom.InnerText = "张三";            user.AppendChild(tom);            //建立子元素            XmlElement jion = doc.CreateElement("name");            jion.SetAttribute("id", "002");            jion.SetAttribute("sex", "男");            jion.InnerText = "司马迁";            user.AppendChild(jion);            //建立子元素            XmlElement jon = doc.CreateElement("name");            jon.SetAttribute("id", "003");            jon.SetAttribute("sex", "女");            jon.InnerText = "小丽";            user.AppendChild(jon);            //添加到根元素            root.AppendChild(user);            //保存            doc.Save(xpath);            //打印           Console.Write(doc.OuterXml);        }        ///         /// 查询信息        ///         /// 
dbs
public List
GetAll() { List
dbs = (from db in doc.Element("books").Elements("book") orderby db.Attribute("id").Value descending select new Book { id = db.Attribute("id").Value.ToString(), bookcategory = db.Attribute("bookcategory").Value.ToString(), image = db.Element("image").Value.ToString(), title = db.Element("title").Value.ToString(), author = db.Element("author").Value.ToString(), publisher = db.Element("publisher").Value.ToString(), ISBN = db.Element("ISBN").Value.ToString(), price = Convert.ToDouble(db.Element("price").Value), num = Convert.ToInt32(db.Element("num").Value) }).ToList(); return dbs; } ///
/// 根据主键查询详细分条信息 /// ///
public List
SelBook(string id) { var query =( from mytable in doc.Descendants("book") where mytable.Attribute("id").Value.ToString() == id select new Book() { id = mytable.Attribute("id").Value, bookcategory = mytable.Attribute("bookcategory").Value, image = mytable.Element("image").Value, title = mytable.Element("title").Value, author = mytable.Element("author").Value, publisher = mytable.Element("publisher").Value, ISBN = mytable.Element("ISBN").Value, price =Convert.ToDouble(mytable.Element("price").Value), num = Convert.ToInt32(mytable.Element("num").Value) }).ToList(); return query; } ///
/// 添加信息 /// ///
public bool Add() { try { XElement root = XElement.Load(filePath); XElement xe = new XElement("book", new XAttribute("id", id), new XAttribute("bookcategory", bookcategory), new XElement("image", image), new XElement("title", title), new XElement("author", author), new XElement("publisher", publisher), new XElement("ISBN", ISBN), new XElement("price", price), new XElement("num", num) ); root.Add(xe); root.Save(filePath); return true; } catch { return false; } } ///
/// 删 /// ///
///
public bool Remove(string id) { XElement xe = (from db in doc.Element("books").Elements("book") where db.Attribute("id").Value == id select db).Single() as XElement; try { xe.Remove(); doc.Save(filePath); return true; } catch { return false; } } ///
/// 修改 /// ///
public bool Modify(string id) { //XElement ex = XElement.Load(@"C:\Users\aa\Desktop\BookShop\BookShop\xml\Books.xml"); //var b = (from f in ex.Descendants("book") where (string)f.Attribute("id").Value.ToString()== id select f).Single(); XElement xe = (from db in doc.Element("books").Elements("book") where db.Attribute("id").Value.ToString() == id select db).Single(); try { xe.Attribute("id").SetValue(id); xe.Element("title").SetValue(title); xe.Element("author").SetValue(author); xe.Attribute("bookcategory").SetValue(bookcategory); xe.Element("publisher").SetValue(publisher); xe.Element("ISBN").SetValue(ISBN); xe.Element("price").SetValue(price); xe.Element("num").SetValue(num); xe.Element("image").SetValue(image); return true; } catch { return false; } } }}
View Code

前台调用

完整的web页面代码:

public partial class WebForm1 : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                this.Bind();            }        }        Book b = new Book();        //查询        public void Bind()        {             var ds = b.GetAll();            GridView1.DataSource = ds;            GridView1.DataBind();        }        //方法一:创建xml并保存        public void Create()        {            string xpath = Server.MapPath("~/xml/peoples.xml");            b.Create(xpath);        }        //方法二        public void Create1()        {            string xpath = Server.MapPath("~/xml/User.xml");            b.Create1(xpath);        }        //分页        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)        {            GridView1.PageIndex = e.NewPageIndex;            this.Bind();        }        //行颜色变化        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)        {            for (int i = 0; i < GridView1.Rows.Count + 1; i++) //执行循环,保证每条数据都可以更新            {                if (e.Row.RowType == DataControlRowType.DataRow)  //首先判断是否是数据行                {                    //当鼠标停留时更改背景色                    e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#999'");                    //当鼠标移开时还原背景色                    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");                }            }        }        //选择        protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)        {            try            {                TextBox3.Text = GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();//编号                string id=TextBox3.Text;                List
query= b.SelBook(id); foreach (var item in query) { TextBox1.Text = item.title;//书名 TextBox2.Text = item.author;//作者 TextBox3.Text = item.id; TextBox4.Text = item.bookcategory;//类别 TextBox5.Text = item.publisher;//出版社 TextBox6.Text = item.ISBN;//出版编号 TextBox7.Text = item.price.ToString();//价格 TextBox8.Text = item.num.ToString();//库存 Image1.ImageUrl = item.image;//图片 } } catch (Exception ex) { Response.Write(ex.Message + ex.StackTrace); } } //删除 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { string id = GridView1.DataKeys[e.RowIndex].Value.ToString(); bool falg = b.Remove(id); if (falg == true) { string s = "
"; Response.Write(s); this.Bind(); } else { string s = "
"; Response.Write(s); } } //添加 protected void Button2_Click(object sender, EventArgs e) { b.title = this.TextBox1.Text; b.author = this.TextBox2.Text; b.id= this.TextBox3.Text; b.bookcategory = this.TextBox4.Text; b.publisher= this.TextBox5.Text; b.ISBN= this.TextBox6.Text; b.price=Convert.ToDouble(this.TextBox7.Text); b.num=Convert.ToInt32(this.TextBox8.Text); string file = FileUpload1.FileName; FileUpload1.SaveAs(Server.MapPath("~/imgbook/" + file)); Image1.ImageUrl = "~/imgbook/" + file; b.image = Image1.ImageUrl; bool falg = b.Add(); if (falg == true) { string s = "
"; Response.Write(s); this.Bind(); } else { string s = "
"; Response.Write(s); } } //修改 protected void Button1_Click(object sender, EventArgs e) { b.title = this.TextBox1.Text; b.author = this.TextBox2.Text; b.id = this.TextBox3.Text; string id = b.id; b.bookcategory = this.TextBox4.Text; b.publisher = this.TextBox5.Text; b.ISBN = this.TextBox6.Text; b.price = Convert.ToDouble(this.TextBox7.Text); b.num = Convert.ToInt32(this.TextBox8.Text); b.image = Image1.ImageUrl; bool falg = b.Modify(id); if (falg == true) { string s = "
"; Response.Write(s); this.Bind(); } else { string s = "
"; Response.Write(s); } } }
View Code

 

将在外君命有所不受

大将在外可以不受君王节制,那么程序的操作也不算一种方法写死的,下面介绍下节点的使用:

查询:

///             /// 查询信息            ///             /// 
dbs
public DataSet Select() { DataSet ds = new DataSet(); StringReader sreader = null; XmlTextReader xtreader = null; try { XmlDocument doc = new XmlDocument(); doc.Load(filePath); sreader = new StringReader(doc.InnerXml); xtreader = new XmlTextReader(sreader); ds.ReadXml(xtreader); return ds; } catch (Exception) { throw; return null; } finally { xtreader.Close(); sreader.Close(); } }
View Code

添加:

///             /// 添加信息            ///             /// 
public bool Add() { try { //在第一个前面插入一条信息 XmlDocument doc = new XmlDocument(); doc.Load(filePath); XmlNode books = doc.SelectSingleNode("books"); XmlElement book = doc.CreateElement("book"); book.SetAttribute("id", id); book.SetAttribute("bookcategory", bookcategory); XmlElement image = doc.CreateElement("image"); image.InnerText = this.image; book.AppendChild(image); XmlElement title = doc.CreateElement("title"); title.InnerText = this.title; book.AppendChild(title); XmlElement author = doc.CreateElement("author"); author.InnerText = this.author; book.AppendChild(author); XmlElement publisher = doc.CreateElement("publisher"); publisher.InnerText = this.publisher; book.AppendChild(publisher); XmlElement ISBN = doc.CreateElement("ISBN"); ISBN.InnerText = this.ISBN; book.AppendChild(ISBN); XmlElement price = doc.CreateElement("price"); price.InnerText = this.price.ToString(); book.AppendChild(price); XmlElement num = doc.CreateElement("num"); num.InnerText = this.num.ToString(); book.AppendChild(num); books.InsertBefore(book, books.FirstChild); doc.Save(filePath); return true; } catch { return false; } }
View Code

删除:

///             /// 删            ///             ///             /// 
public bool Remove(string id) { XElement xe = (from db in doc.Element("books").Elements("book") where db.Attribute("id").Value == id select db).Single() as XElement; try { xe.Remove(); doc.Save(filePath); return true; } catch { return false; } }
View Code

修改:

///             /// 修改            ///             /// 
public bool Modify(string id) { //XElement ex = XElement.Load(@"C:\Users\aa\Desktop\BookShop\BookShop\xml\Books.xml"); //var b = (from f in ex.Descendants("book") where (string)f.Attribute("id").Value.ToString()== id select f).Single(); XElement xe = (from db in doc.Element("books").Elements("book") where db.Attribute("id").Value.ToString() == id select db).Single(); try { xe.Attribute("id").SetValue(id); xe.Element("title").SetValue(title); xe.Element("author").SetValue(author); xe.Attribute("bookcategory").SetValue(bookcategory); xe.Element("publisher").SetValue(publisher); xe.Element("ISBN").SetValue(ISBN); xe.Element("price").SetValue(price); xe.Element("num").SetValue(num); xe.Element("image").SetValue(image); return true; } catch { return false; } }
View Code

 

凯歌而归

最后说明一下,本程序对xml操作,采用两种方法,经过测试都没问题。详细完整的代码在讲解过程中已经附录!

转载地址:http://dkxna.baihongyu.com/

你可能感兴趣的文章
java测试邮箱是否_javaWEB邮件测试
查看>>
java里booelan_Java Web应用开发技术与案例教程 教学课件 张继军 第4章_JDBC数据库访问技术.ppt...
查看>>
php mysql记录用户行为_用户参与记录存储的演变_PHP教程
查看>>
python中使用缩进来体现代码之间的逻辑关系_Python使用缩进来体现代码之间的逻辑关系。...
查看>>
python图像对比度拉伸_python库skimage 图像直方图均衡化、自适应均衡化、对比度拉伸实现...
查看>>
java判断是不是disable_Java Compiler disable()方法与示例
查看>>
php 发送 二进制,PHP处理二进制数据的实现方法
查看>>
用php写上传文件的代码,php多文件上传实现代码
查看>>
php发送邮件怎么配置,php 配置smtp发送邮件
查看>>
java文件名要和什么一致,Java源程序的文件名一定要与文件中某个类的名称一致。...
查看>>
c php结合,腾讯熊月:企点将php嵌入到高性能C/C++框架运行的探索实践
查看>>
php图片克隆,php实现对象克隆的方法
查看>>
java myqq ui,用Java Swing写一个登录界面
查看>>
java添加录音,java录音程序
查看>>
php xml 没有报文头,解决php输出xml设置header头Content-type:text/xml的方法
查看>>
php简化URL路径,php – 修改(简化)主题标题以便在url中显示
查看>>
php设计的个人页面成品,PHP仿个人博客(1)数据库与界面设计
查看>>
php函数改变表格颜色,php把一个颜色变深的函数示例开发详解
查看>>
go php 组合,Go语言组合和方法集
查看>>
matlab求图像峰度与斜度,python中的图像偏斜和峰度
查看>>