C # sample code sharing to implement additions and deletions of XML documents

Source: Internet
Author: User
This article mainly introduced the C # Implementation of XML document deletion and modification function, combined with examples of the creation of XML documents and C # for XML document loading and deletion and modification of the operation skills, the need for friends can refer to the next

In this paper, we describe the function of C # to implement additions and deletions of XML documents. Share to everyone for your reference, as follows:

1. Create an instance XML file (books.xml)

<?xml version= "1.0" encoding= "iso-8859-1"?><bookstore> <book id= "1" category= "COOKING" > <title Lang= "en" >everyday italian</title> <author>giada De laurentiis</author> <year>2005</ year> <price>30.00</price> </book> <book id= "2" category= "Children" > <title lang= "en" >harry potter</title> <author>j K. rowling</author> <year>2005</year> <price> 29.99</price> </book> <book id= "3" category= "WEB" > <title lang= "en" >xquery Kick start</ title> <author>james mcgovern</author> <author>per bothner</author> <author>Kurt  cagle</author> <author>james linn</author> <author>vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> <book id= "4" category= "WEB" > < Title lang= "en" >learning xml</title> <author>erik T. ray</author> <year>2003</year> <price>39.95</price> </book></bookstore >

2. Create book Information entity class (BookInfo.cs)

public class bookinfo{//<summary>///  book ID//</summary> public  int BookId {set; get;} //<summary>///Book name///  </summary> public  string Title {set; get;}  <summary>////book category///  </summary> Public  string category {set; get;}  <summary>///Book language///  </summary> public  string Language {set; get;}  <summary>///book author///  </summary> public  string Author {set; get;}  <summary>///Publishing time///  </summary> public string year  {set; get;}  <summary>///Sales price///  </summary> Public decimal prices  {set; get;}}

3. Create book Information business logic class (BookInfoBLL.cs)

Using System.Xml; Reference related files public class bookinfobll{private string _basepath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @ "/xml/books.xml";  XML file path private XmlDocument _booksxmldoc = null; Create XML Document Object public Bookinfobll () {try {_booksxmldoc = new XmlDocument ();//Initialize XML Document Object _booksxmldoc.loa   D (_basepath); Load the specified XML document} catch (Exception ex) {throw new Exception ("Error loading XML document:" + ex.)    Message); }}///<summary>///Get a list of books (check)///</summary>//<param name= "param" > Parameter conditions </param>//< Returns> Books list </returns> public list<bookinfo> getbookinfolist (BookInfo param) {list<bookinfo> bo    Okinfolist = new list<bookinfo> (); String XPath = "Bookstore/book"; The default gets all books if (param. BookId! = 0)//based on book ID query {xPath = String.Format ("/bookstore/book[@id = ' {0} ']", Param.    BOOKID); } else if (! String.IsNullOrEmpty (param. category)//query according to book type {XPath = String.Format ("/bookstore/book[@category = ' {0} '] ", Param.    Category); } else if (! String.IsNullOrEmpty (param. Title)//According to the book name query {xPath = String.Format ("/bookstore/book[title= ' {0} ']", Param.    Title);    } XmlNodeList booksxmlnodelist = _booksxmldoc.selectnodes (XPath);      foreach (XmlNode booknode in booksxmlnodelist) {BookInfo BookInfo = new BookInfo (); Bookinfo.bookid = Convert.ToInt32 (booknode.attributes["id"]. Value); Gets the property value Bookinfo.category = booknode.attributes["Category"].      Value; Bookinfo.language = Booknode.selectsinglenode ("title"). attributes["Lang"]. Value; Gets the property value of the child node Bookinfo.title = Booknode.selectsinglenode ("Title").   InnerText; Gets the element value Bookinfo.author = Booknode.selectsinglenode ("Author").      InnerText; Bookinfo.year = Booknode.selectsinglenode ("year").      InnerText; Bookinfo.price = Convert.todecimal (Booknode.selectsinglenode ("Price").      InnerText);    Bookinfolist.add (BookInfo);  } return bookinfolist; }///<summary>//Add BooksInformation (Increase)///</summary>//<param name= "param" ></param>//<returns></returns> public Boo    L addbookinfo (BookInfo param) {bool result = false; XmlNode root = _booksxmldoc.selectsinglenode ("bookstore");    Find <bookstore>//create node XmlElement bookxmlelement = _booksxmldoc.createelement ("book");    XmlElement titlexmlelement = _booksxmldoc.createelement ("title");    XmlElement authorxmlelement = _booksxmldoc.createelement ("author");    XmlElement yearxmlelement = _booksxmldoc.createelement ("year");    XmlElement pricexmlelement = _booksxmldoc.createelement ("price"); Assigns a value to the node Bookxmlelement.setattribute ("id", param.    Bookid.tostring ()); Bookxmlelement.setattribute ("category", Param.    Category); Titlexmlelement.innertext = param. Title; add element value Titlexmlelement.setattribute ("lang", param) to the node. Language);//Add the attribute value Authorxmlelement.innertext = param to the node.    Author; Yearxmlelement.innertext = param.    year; Pricexmlelement.innertext = param. PriCe.    ToString ();    AppendChild adds the specified node to the end of the node's child nodes list Bookxmlelement.appendchild (titlexmlelement);    Bookxmlelement.appendchild (authorxmlelement);    Bookxmlelement.appendchild (yearxmlelement);    Bookxmlelement.appendchild (pricexmlelement); Root.    AppendChild (bookxmlelement);    _booksxmldoc.save (_basepath);    result = true;  return result; }//<summary>//Modify the book Information (change)///</summary>//<param name= "param" ></param>//<returns    ></returns> public bool Editbookinfo (BookInfo param) {bool result = false; if (param. bookid>0) {String xPath = String.Format ("/bookstore/book[@id = ' {0} ']", Param.      BOOKID);      XmlNode Editxmlnode = _booksxmldoc.selectsinglenode (XPath);      XmlElement editxmlelement = (XmlElement) Editxmlnode; if (editxmlelement! = null) {editxmlelement.attributes["category"]. Value = param.        Category; Editxmlelement.selectsinglenode ("title"). attributes["Lang"]. Value = param.    Language;    Editxmlelement.selectsinglenode ("title"). InnerText = param.        Title; Editxmlelement.selectsinglenode ("Author"). InnerText = param.        Author; Editxmlelement.selectsinglenode ("Year"). InnerText = param.        year; Editxmlelement.selectsinglenode ("Price"). InnerText = param.        Price.tostring ();        _booksxmldoc.save (_basepath);      result = true;  }} return result; }///<summary>//delete book information (delete)///</summary>//<param name= "param" ></param>//<returns    ></returns> public bool Deletebookinfo (BookInfo param) {bool result = false; if (param. BookId > 0) {string xPath = String.Format ("/bookstore/book[@id = ' {0} ']", Param.      BOOKID);      XmlNode Delxmlnode = _booksxmldoc.selectsinglenode (XPath); if (Delxmlnode! = null) {_booksxmldoc.selectsinglenode ("bookstore").  RemoveChild (Delxmlnode);        Removes the specified child node _booksxmldoc.save (_basepath);      result = true;  }} return result; }}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.