将 Excel CSV 转换为 XML 格式 Asp.net C#

Convert Excel CSV to XML format Asp.net C#

我正在寻找一种方法将我的 CSV 文件转换为 XML 格式并最终在 HTML table 中显示 XML。我在 Stack Overflow 上找到了执行此操作的各种方法。首先,我使用的技术是:ASP.NET MVC 4.0 和 C# 中的 WCF REST 服务。我发现了多种将 CSV 文件转换为 XML 格式的方法; XSLT、Linq to CSV、RegEx 和 Filehelper 库。可能还有我不知道的技术

CSV 格式:

ORDER_NUMBER PRODUCT_ID 
12-34-4567 12345 
12-34-4567 12345
12-34-4567 12345 
12-34-4567 12345 
12-34-4567 12345 
12-34-4567 12345

你对我应该采取什么方法来做这件事有什么看法?

var lines = File.ReadAllLines(@"C:\text.csv");

    var xml = new XElement("TopElement",
       lines.Select(line => new XElement("Item",
          line.Split(';')
              .Select((column, index) => new XElement("Column" + index, column)))));

    xml.Save(@"C:\xmlout.xml"); (from:whosebug.com/questions/3069661/convert-csv-file-to-xml?rq=1)

我会先从 CSV 转换为本机 C# 对象。

public class Order
{
    public string OrderNumber {get; set;}
    public string ProductId {get; set;}
}

public List<Order> GetOrdersFromCSV(string csv)
{
    //This should be a good place to use FileHelpers, but since the format is so simple we're going to parse it ourselves instead.
    string[] lines = csv.Replace("\r\n","\n").Split('\n'); //Split to individual lines
    List<Order> orders = new List<Order>(); //Create an object to hold the orders
    foreach(string line in lines) //Loop over the lines
    {
        Order order=new Order(); //Create an empty new order object to hold the order
        order.OrderNumber = line.Split(',')[0]; //get first column and put it in the Order as the OrderNumber
        order.ProductId = line.Split(',')[1]; //get second column
        orders.Add(order); //Add the order to the list of orders that we'll return
    }
    return orders;
}

请注意,除了非常简单的 CSV 文件外,这不会处理任何东西,推出您自己的解析器通常不是一个好主意,这就是为什么我建议现有的库,如 FileHelpers。切换到更强大的系统可能是个好主意。

现在您已经有了 Order 个对象的列表,您可以将它变成 XML。我们将使用 XDocument class.

public static XDocument ConvertToXDocument(IEnumerable<Order> orders) //accept IEnumerable of orders because don't care if it's a list or not as long as we can enumerate over it
{
    XDocument doc =
        new XDocument(
             new XElement("Orders",orders.Select(o =>
                 new XElement("Order",
                      new XAttribute("OrderNo", o.OrderNumber),
                      new XAttribute("ProductId", o.ProductId)))));
    return doc;
}

您可以在 ConvertToXDocument() 的结果上调用 .ToString() 函数来获取您的 XML 字符串。

您还可以将 GetOrdersFromCSV() 的结果传递给 MVC to generate some HTML using Razor 中的视图。您的视图可能如下所示:

@model IEnumberable<Order>

<table>
    <tr>
        <th>Order Number</th>
        <th>Product Id</th>
    </tr>
@foreach(Order order in Orders)
    {
    <tr>
        <td>@order.OrderNumber</td>
        <td>@order.ProductId</td>
    </tr>
    }
</table>

我构建了一个显示所有内容的控制台应用程序(HTML 部分除外)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleApplication
    {
    public class Class1
        {
        public static string CSVInput = @"12-34-4567,12345 
12-34-4567,12345
12-34-4567,12345 
12-34-4567,12345 
12-34-4567,12345 
12-34-4567,12345";

        public static void Main(string[] args)
            {
            var orders = GetOrdersFromCSV(CSVInput);
            string xml = ConvertToXDocument(orders).ToString();
            Console.WriteLine(xml);
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
            }

        public static List<Order> GetOrdersFromCSV(string csv)
            {
            //This should be a good place to use FileHelpers, but since the format is so simple we're going to parse it ourselves instead.
            string[] lines = csv.Replace("\r\n", "\n").Split('\n');
            List<Order> orders = new List<Order>();
            foreach (string line in lines)
                {
                Order order = new Order();
                order.OrderNumber = line.Split(',')[0]; //get first column
                order.ProductId = line.Split(',')[1]; //get second column
                orders.Add(order);
                }
            return orders;
            }
        public static XDocument ConvertToXDocument(List<Order> orders)
            {
            XDocument doc =
      new XDocument(
        new XElement("Orders",
            orders.Select(o => new XElement("Order", new XAttribute("OrderNo", o.OrderNumber), new XAttribute("ProductId", o.ProductId)))));
            return doc;
            }
        }
    public class Order
        {
        public string OrderNumber { get; set; }
        public string ProductId { get; set; }
        }

    }