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

时间:2015-01-19 19:20:30

标签: c# asp.net csv xml-parsing

我正在寻找一种方法将CSV文件转换为XML格式,并最终在HTML表格中显示XML。我已经在Stack Overflow上找到了各种方法。首先,我使用的技术是:使用C#中的WCF REST服务的ASP.NET MVC 4.0。我找到了将CSV文件转换为XMLformat的各种方法; XSLT,Linq到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:stackoverflow.com/questions/3069661/convert-csv-file-to-xml?rq=1)

1 个答案:

答案 0 :(得分:0)

我首先会从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类。

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;
}

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

您还可以将GetOrdersFromCSV()的结果传递到MVC中的视图,以使用Razor生成一些HTML。您的观点可能如下所示:

@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; }
        }

    }