【XML】xml封装方法

前端之家收集整理的这篇文章主要介绍了【XML】xml封装方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

起兵有因:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style=" width:1200px; height:500px; margin:20px auto">
    
        <asp:GridView ID="GridView1" runat="server" Height="300px" Width="1000px" AllowPaging="True" AutoGenerateColumns="False" HorizontalAlign="Center" onpageindexchanging="GridView1_PageIndexChanging" PageSize="6" onrowdatabound="GridView1_RowDataBound" onselectedindexchanging="GridView1_SelectedIndexChanging" DataKeyNames="id" onrowdeleting="GridView1_RowDeleting">
          
            <Columns>
                <asp:BoundField DataField="id" HeaderText="图书编号" />
                <asp:BoundField DataField="bookcategory" HeaderText="类别" />
                <asp:TemplateField HeaderText="图片">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1"  runat="server" Text='<%# Eval("image") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Image ID="Image1"  runat="server" ImageUrl='<%# Eval("image") %>' Height="60" Width="80" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="title" HeaderText="书名" />
                <asp:BoundField DataField="author" HeaderText="作者" />
                <asp:BoundField DataField="publisher" HeaderText="出版社" />
                <asp:BoundField DataField="ISBN" HeaderText="图书编码" />
                <asp:BoundField DataField="price" HeaderText="价格" />
                <asp:BoundField DataField="num" HeaderText="库存" />
                <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
                <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
            </Columns>
          
            <HeaderStyle BackColor="Black" Height="30px" BorderColor="Black" ForeColor="White" />
            <PagerSettings FirstPageText="首页" LastPageText="尾页" NextPageText="下一页" PrevIoUsPageText="上一页" Mode="NextPrevIoUsFirstLast" />
            <PagerStyle BackColor="Black" ForeColor="White" />
        </asp:GridView>
    
    </div>
     <div style=" margin-top:20px; width:1000px; height:500px; margin:20px auto; ">
         <table style=" width:100%; height:300px; margin-top:10px;">
             <tr style="width:50% ;">
             <td rowspan="2" >
                 <asp:Image ID="Image1" Width="200px" Height="250px" runat="server" />
             </td>
             </tr>
             <tr>
               <td style="height: 270px">
               <table>
                 <tr><td>书名:</td><td>
                 <asp:TextBox ID="TextBox1" runat="server" MaxLength="15"></asp:TextBox>
                 </td></tr>
             <tr><td>作者:</td><td>
                 <asp:TextBox ID="TextBox2" runat="server" MaxLength="15"></asp:TextBox>
                 </td></tr>
             <tr><td>图书编号:</td><td>
                 <asp:TextBox ID="TextBox3" runat="server" MaxLength="15"></asp:TextBox>
                 </td></tr>
             <tr><td>图书类别:</td><td>
                 <asp:TextBox ID="TextBox4" runat="server" MaxLength="15"></asp:TextBox>
                 </td></tr>
             <tr><td>出版社:</td><td>
                 <asp:TextBox ID="TextBox5" runat="server" MaxLength="15"></asp:TextBox>
                 </td></tr>
             <tr><td>出版编号:</td><td>
                 <asp:TextBox ID="TextBox6" runat="server" MaxLength="15"></asp:TextBox>
                 </td></tr>
             <tr><td>价格:</td><td>
                 <asp:TextBox ID="TextBox7" runat="server" MaxLength="15" TextMode="Number"></asp:TextBox>
                </td></tr>
             <tr><td>库存:</td><td>
                 <asp:TextBox ID="TextBox8" runat="server" MaxLength="15" TextMode="Number"></asp:TextBox>
                </td></tr>
                 <tr><td>图片:</td><td>
                     <asp:FileUpload ID="FileUpload1"  runat="server" BackColor="White" Width="228px" />
                 </td></tr>
               </table>
               </td><td style="height: 270px"></td>
             </tr>
             <tr>
             <td colspan="2" style=" text-align:center;">
                 <span><asp:Button ID="Button1" runat="server" Text="修改" onclick="Button1_Click" /></span>
                 <span style=" margin-left:20px;">
                 <asp:Button ID="Button2" runat="server" Text="添加" onclick="Button2_Click" /></span> 
                 </td>
             </tr>
            </table>
    </div>
    </form>
</body>
</html>
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

查询

/// <summary>
        /// 查询信息 /// </summary>
        /// <returns>dbs</returns>
        public List<Book> GetAll() { List<Book> 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

修改

/// <summary>
        /// 修改 /// </summary>
        /// <returns></returns>
        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

添加

/// <summary>
        /// 添加信息 /// </summary>
        /// <returns></returns>
        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

删除

/// <summary>
        ////// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        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","10") ) ) ); books.Save(xpath); Console.Write(books); } //方法
        public void Create1(string xpath) { XmlDocument doc = new XmlDocument(); //创建指令
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0",""); jon.InnerText = "小丽"; user.AppendChild(jon); //添加到根元素
 root.AppendChild(user); //保存
 doc.Save(xpath); //打印
 Console.Write(doc.OuterXml); } /// <summary>
        /// 查询信息 /// </summary>
        /// <returns>dbs</returns>
        public List<Book> GetAll() { List<Book> dbs = (from db in doc.Element("books").Elements("book") orderby db.Attribute("id").Value descending select new Book { id = db.Attribute("id").Value.ToString(),num = Convert.ToInt32(db.Element("num").Value) }).ToList(); return dbs; } /// <summary>
        /// 根据主键查询详细分条信息 /// </summary>
        /// <returns></returns>
        public List<Book> 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; } /// <summary>
        /// 添加信息 /// </summary>
        /// <returns></returns>
        public bool Add() { try { XElement root = XElement.Load(filePath); XElement xe = new XElement("book",num) ); root.Add(xe); root.Save(filePath); return true; } catch { return false; } } /// <summary>
        ////// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        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; } } /// <summary>
        /// 修改 /// </summary>
        /// <returns></returns>
        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<Book> 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 = "<script>alert('删除成功!')</script>"; Response.Write(s); this.Bind(); } else { string s = "<script>alert('删除失败!')</script>"; 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 = "<script>alert('添加成功!')</script>"; Response.Write(s); this.Bind(); } else { string s = "<script>alert('添加失败!')</script>"; 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 = "<script>alert('修改成功!')</script>"; Response.Write(s); this.Bind(); } else { string s = "<script>alert('修改失败!')</script>"; Response.Write(s); } } }
View Code

将在外君命有所不受

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

查询

/// <summary>
            /// 查询信息 /// </summary>
            /// <returns>dbs</returns>
            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

添加

/// <summary>
            /// 添加信息 /// </summary>
            /// <returns></returns>
            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

删除

/// <summary>
            ////// </summary>
            /// <param name="id"></param>
            /// <returns></returns>
            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

修改

/// <summary>
            /// 修改 /// </summary>
            /// <returns></returns>
            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操作,采用两种方法,经过测试都没问题。详细完整的代码在讲解过程中已经附录!

原文链接:https://www.f2er.com/xml/293771.html

猜你在找的XML相关文章