星期六, 12月 19, 2020

[C#] csv 檔案轉換為 XML

根據官方該篇 - 如何從 CSV 檔案產生 XML (LINQ to XML) 的練習
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace XMLConvert
{
    class Program
    {
        static void Main(string[] args)
        {
            string csvFileFullName = @"D:\Demo\CSV2XML.csv";

            CSVFileCreate(csvFileFullName);

            List<string> source = CSVReader(csvFileFullName);

            XDocument xDoc = new XDocument
            (
                new XDeclaration("1.0", "utf-8", "yes"),
                new XComment("Linq2XML"),
                new XElement
                (
                    "Root",
                    source.Select(s => s.Split(','))
                        .Select
                        (e =>
                            new XElement("Customer", new XAttribute("CustomerID", e[0]),
                                new XElement("CompanyName", e[1]),
                                new XElement("ContactName", e[2]),
                                new XElement("ContactTitle", e[3]),
                                new XElement("Phone", e[4]),
                                new XElement("FullAddress",
                                    new XElement("Address", e[5]),
                                    new XElement("City", e[6]),
                                    new XElement("Region", e[7]),
                                    new XElement("PostalCode", e[8]),
                                    new XElement("Country", e[9]))))
                        )
            );

            xDoc.Save(@"D:\Demo\CSV2XML.xml");
        }

        private static void CSVFileCreate(string csvFileFullName)
        {
            string csvString = @"GREAL,Great Lakes Food Market,Howard Snyder,Marketing Manager,(503) 555-7555,2732 Baker Blvd.,Eugene,OR,97403,USA
HUNGC,Hungry Coyote Import Store,Yoshi Latimer,Sales Representative,(503) 555-6874,City Center Plaza 516 Main St.,Elgin,OR,97827,USA
LAZYK,Lazy K Kountry Store,John Steel,Marketing Manager,(509) 555-7969,12 Orchestra Terrace,Walla Walla,WA,99362,USA
LETSS,Let's Stop N Shop,Jaime Yorres,Owner,(415) 555-5938,87 Polk St. Suite 5,San Francisco,CA,94117,USA";

            File.WriteAllText(csvFileFullName, csvString);
        }

        private static List<string> CSVReader(string csvFileFullName)
        {
            return File.ReadAllLines(csvFileFullName).ToList();
        }
    }
}

結果截圖只顯示一筆資料而已

[C#] csv 檔案轉換為 XML

沒有留言:

張貼留言