Dynamically generate book information XML files from C #

Source: Internet
Author: User
Dynamically generate the book information XML file (books.xml) through C #, with the following file:

<?xml version= "1.0" encoding= "iso-8859-1"?>   <bookstore>     <book id= "1" category= "Children" >   <title>harry potter</title>   <author>j K. rowling</author>   < publishdate>2005-08-15</publishdate>   <price>29.99</price>   </book>     < Book id= "2" category= "WEB" >   <title>learning xml</title>   <author>erik T. Ray</author >   <publishDate>2003-10-18</publishDate>   <price>39.95</price>   </ Book>     </bookstore>

Method 1: Use StringBuilder to stitch the XML

<summary>///create book information XML///</summary> public void Createbookxml (string fileName) {StringBuilder Xmlresul t = new StringBuilder ("<?xml version=\" 1.0\ "encoding=\" utf-8\ "?>"); List<bookinfo> Booklist = Getbooklist ();  Gets the list of books if (Booklist! = null && booklist.count > 0) {xmlresult.append ("<bookstore>"); foreach (BookInfo Book in Booklist) {Xmlresult.appendformat ("<book id=\"} {0}\ "category=\" {1}\ ">", Book. BookId, book. Category); Xmlresult.appendformat ("<title>{0}</title>", book. Title); Xmlresult.appendformat ("<author>{0}</author>", book. Author); Xmlresult.appendformat ("<publishDate>{0}</publishDate>", book. Publishdate.tostring ("Yyyy-mm-dd")); Xmlresult.appendformat ("<price>{0}</price>", book. Price); Xmlresult.append ("</book>"); } xmlresult.append ("</bookstore>"); }//write to file try {//1. create file stream FileStream FileStream = new FileStream (FileName, FileMode.Create);//2. Create writer StreamWriter sTreamwriter = new StreamWriter (fileStream); 3. Write content to file Streamwriter.writeline (Xmlresult); 4. Turn off the writer StreamWriter.Close (); 5. Close file stream filestream.close (); } catch (Exception e) {}}

Method 2: Create XML using the XmlTextWriter class

<summary>//create book information XML///</summary>//<param name= "fileName" ></param> public void Create Bookxml (string filename) {try {FileStream FileStream = new FileStream (FileName, FileMode.Create); XmlTextWriter writer = new XmlTextWriter (FileStream, Encoding.UTF8); List<bookinfo> Booklist = Getbooklist (); Get a list of books if (Booklist! = null && booklist.count > 0) {writer. WriteStartDocument (); Writer. WriteStartElement ("bookstore"); Create a parent node foreach (BookInfo book in Booklist) {writer. WriteStartElement ("book"); Create a child node writer. WriteAttributeString ("id", book.) Bookid.tostring ()); Add property writer. WriteAttributeString ("category", book.) Category); Book name node writer. WriteStartElement ("title"); Writer. WriteValue (book. Title); Node assignment writer. WriteEndElement (); Book author node writer. WriteStartElement ("author"); Writer. WriteValue (book. Author); Writer. WriteEndElement (); Publishing Time node writer. WriteStartElement ("Publishdate"); Writer. WriteValue (book. Publishdate.tostring ("Yyyy-mm-dd")); Writer. WriteEndElement (); Sales price node writer. WriteStartElement ("Price"); Writer. WriteValue (book. Price); Writer. WriteEndElement (); Writer. WriteEndElement (); Child node End} writer. WriteEndElement (); Parent node End} writer. WriteEndDocument (); Writer. Close (); Filestream.close (); } catch (Exception e) {}}

XmlTextWriter class: A writer that provides a fast, non-cached, forward-only method that generates a stream or file that contains XML data.
WriteStartDocument () method: writes the declaration of the XML.
WriteEndDocument () method: Closes any open elements or attributes and sets the writer back to the Start state.
WriteStartElement (String localname) method: Creates the start of a node.
WriteAttributeString (String localname, String value) method: Adds a property to the node.
WriteValue (Value) method: Assigns a value to a node.

3, other code

3.1 get book list

<summary>///Get a list of books///   </summary>/   <returns></returns>   public List <BookInfo> getbooklist ()   {   list<bookinfo> Booklist = new list<bookinfo> ();   BookInfo Book1 = new BookInfo () {   BookId = 1,   Category = "Children",   Title = "Harry Potter",   Author = "J K. Rowling ",   publishdate = new DateTime (2005,08,15), Price   = 29.99   };   Booklist.add (BOOK1);   BookInfo book2 = new BookInfo ()   {   BookId = 2,   Category = "WEB",   Title = "Learning XML",   Author = "Erik T. Ray",   publishdate = new DateTime (2003,10,18), Price   = 39.95   };   Booklist.add (BOOK2);   return booklist;   }

3.2 Book Information entity class

<summary>////   Library Information entity class///   </summary> public   class BookInfo   {public   int BookId { Set Get }//Book ID public   string Title {set; get;}//Book name public   string category {set; get;}//Book category public   string Au Thor {set; get;}//Book author public   DateTime publishdate {set; get;}//Publication time public   Double price {set; get;}//Sales Prices Lattice   }

The above is through the C # dynamic generation of book information XML file content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.