1. 程式人生 > >C#動態生成XML

C#動態生成XML

str 出版 打開 class append 表示 com gpo copyto

通過C#動態生成圖書信息XML文件(Books.xml),文件如下:

  1. <?xml version="1.0" encoding="iso-8859-1"?>
  2. <bookstore>
  3. <book id="1" category="CHILDREN">
  4. <title>Harry Potter</title>
  5. <author>J K. Rowling</author>
  6. <publishDate>2005-08-15</publishDate>
  7. <price>29.99</price>
  8. </book>
  9. <book id="2" category="WEB">
  10. <title>Learning XML</title>
  11. <author>Erik T. Ray</author>
  12. <publishDate>2003-10-18</publishDate>
  13. <price>39.95</price>
  14. </book>
  15. </bookstore>
  16. 方法1:使用StringBuilder拼接XML
    1. /// <summary>
    2. /// 創建圖書信息XML
    3. /// </summary>
    4. public void CreateBookXML(string fileName)
    5. {
    6. StringBuilder xmlResult = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    7. List<BookInfo> bookList = GetBookList(); //獲取圖書列表
    8. if (bookList != null && bookList.Count > 0)
    9. {
    10. xmlResult.Append("<bookstore>");
    11. foreach (BookInfo book in bookList)
    12. {
    13. xmlResult.AppendFormat("<book id=\"{0}\" category=\"{1}\">", book.BookId, book.Category);
    14. xmlResult.AppendFormat("<title>{0}</title>", book.Title);
    15. xmlResult.AppendFormat("<author>{0}</author>", book.Author);
    16. xmlResult.AppendFormat("<publishDate>{0}</publishDate>", book.PublishDate.ToString("yyyy-MM-dd"));
    17. xmlResult.AppendFormat("<price>{0}</price>", book.Price);
    18. xmlResult.Append("</book>");
    19. }
    20. xmlResult.Append("</bookstore>");
    21. }
    22. //寫入文件
    23. try
    24. {
    25. //1.創建文件流
    26. FileStream fileStream = new FileStream(fileName, FileMode.Create);
    27. //2.創建寫入器
    28. StreamWriter streamWriter = new StreamWriter(fileStream);
    29. //3.將內容寫入文件
    30. streamWriter.WriteLine(xmlResult);
    31. //4.關閉寫入器
    32. streamWriter.Close();
    33. //5.關閉文件流
    34. fileStream.Close();
    35. }
    36. catch (Exception e)
    37. { }
    38. }
    39. 方法2:使用XmlTextWriter類創建XML
      1. /// <summary>
      2. /// 創建圖書信息XML
      3. /// </summary>
      4. /// <param name="fileName"></param>
      5. public void CreateBookXML(string fileName)
      6. {
      7. try
      8. {
      9. FileStream fileStream = new FileStream(fileName, FileMode.Create);
      10. XmlTextWriter writer = new XmlTextWriter(fileStream, Encoding.UTF8);
      11. List<BookInfo> bookList = GetBookList(); //獲取圖書列表
      12. if (bookList != null && bookList.Count > 0)
      13. {
      14. writer.WriteStartDocument();
      15. writer.WriteStartElement("bookstore"); //創建父節點
      16. foreach (BookInfo book in bookList)
      17. {
      18. writer.WriteStartElement("book"); //創建子節點
      19. writer.WriteAttributeString("id", book.BookId.ToString()); //添加屬性
      20. writer.WriteAttributeString("category", book.Category);
      21. //圖書名稱節點
      22. writer.WriteStartElement("title");
      23. writer.WriteValue(book.Title); //節點賦值
      24. writer.WriteEndElement();
      25. //圖書作者節點
      26. writer.WriteStartElement("author");
      27. writer.WriteValue(book.Author);
      28. writer.WriteEndElement();
      29. //出版時間節點
      30. writer.WriteStartElement("publishDate");
      31. writer.WriteValue(book.PublishDate.ToString("yyyy-MM-dd"));
      32. writer.WriteEndElement();
      33. //銷售價格節點
      34. writer.WriteStartElement("price");
      35. writer.WriteValue(book.Price);
      36. writer.WriteEndElement();
      37. writer.WriteEndElement(); //子節點結束
      38. }
      39. writer.WriteEndElement(); //父節點結束
      40. }
      41. writer.WriteEndDocument();
      42. writer.Close();
      43. fileStream.Close();
      44. }
      45. catch (Exception e)
      46. { }
      47. }
      48. XmlTextWriter類:表示提供快速、非緩存、只進方法的編寫器,該方法生成包含 XML 數據的流或文件。
        WriteStartDocument()方法:編寫XML的聲明。
        WriteEndDocument()方法:關閉任何打開的元素或屬性並將編寫器重新設置為 Start 狀態。
        WriteStartElement(string localName)方法:創建一個節點的開始。
        WriteAttributeString(string localName, string value)方法:給節點添加屬性。
        WriteValue(value)方法:給節點賦值。
      49. 獲取圖書列表
        1. /// <summary>
        2. /// 獲取圖書列表
        3. /// </summary>
        4. /// <returns></returns>
        5. public List<BookInfo> GetBookList()
        6. {
        7. List<BookInfo> bookList = new List<BookInfo>();
        8. BookInfo book1 = new BookInfo() {
        9. BookId = 1,
        10. Category = "CHILDREN",
        11. Title = "Harry Potter",
        12. Author = "J K. Rowling",
        13. PublishDate = new DateTime(2005,08,15),
        14. Price = 29.99
        15. };
        16. bookList.Add(book1);
        17. BookInfo book2 = new BookInfo()
        18. {
        19. BookId = 2,
        20. Category = "WEB",
        21. Title = "Learning XML",
        22. Author = "Erik T. Ray",
        23. PublishDate = new DateTime(2003,10,18),
        24. Price = 39.95
        25. };
        26. bookList.Add(book2);
        27. return bookList;
        28. }
        29. 圖書信息實體類

          [csharp] view plain copy
          1. /// <summary>
          2. /// 圖書信息實體類
          3. /// </summary>
          4. public class BookInfo
          5. {
          6. public int BookId { set; get; } //圖書ID
          7. public string Title { set; get; } //圖書名稱
          8. public string Category { set; get; } //圖書分類
          9. public string Author { set; get; } //圖書作者
          10. public DateTime PublishDate { set; get; } //出版時間
          11. public Double Price { set; get; } //銷售價格
          12. }

C#動態生成XML