2017年8月19日 星期六

[C#] XML文件讀取、寫入方法

假日沒事在家用功,複習一些基本的東西順便記錄下來
有些太久沒用真得很容易忘記
內容參考《Professional C#6 and .Net Core 1.0》
================================================
XML文件

<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<bookstore>
  <book genre="autobiography" publicationdate="1991" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>
================================================
程式碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;

namespace XmlExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var doc = new XmlDocument();

            // 讀取xml
            using (FileStream stream = File.OpenRead("books.xml"))
            {
                doc.Load(stream);

                XmlNodeList priceNodes = doc.GetElementsByTagName("price");

                foreach (XmlNode node in priceNodes)
                {
                    // 修改內容
                    node.InnerText = "100";
                }
            }

            // 寫入xml
            var settings = new XmlWriterSettings
            {
                Indent = true,
                IndentChars = "\t",
                NewLineChars = Environment.NewLine
            };
            using (StreamWriter streamWriter = File.CreateText("newbooks.xml"))
            using (XmlWriter writer = XmlWriter.Create(streamWriter, settings))
            {
                doc.WriteContentTo(writer);
            }

            Console.WriteLine("Finish");
            Console.ReadLine();
        }
    }
}

沒有留言:

張貼留言