CSV转换为XML时,CSV包含字符和数字数据 [英] Convert CSV to XML when CSV contains both character and number data

查看:156
本文介绍了CSV转换为XML时,CSV包含字符和数字数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

线程,我就如何CSV解析基本信息创建XML。遗憾的是,文本字段(所有引号括起来)有时包含逗号,所以line.split('')给了我太多的列。我无法弄清楚如何解析CSV所以line.split('')逗号区分文本字段中,而逗号分隔的字段。如何做到这一点有什么想法?

From this thread, I got the basic info on how to parse CSV to create XML. Unfortunately, the text fields (all enclosed in quotes) sometimes contain commas, so line.split(',') gives me too many columns. I can't figure out how to parse the CSV so line.split(',') distinguishes between commas within a text field, and commas separating fields. Any thoughts on how to do that?

谢谢!

推荐答案

去抓住这个代码: http://geekswithblogs.net/mwatson/archive/

Go grab this code: http://geekswithblogs.net/mwatson/archive/2004/09/04/10658.aspx

然后用SplitCSV(行),喜欢更换line.Split()

Then replace line.Split(",") with SplitCSV(line), like:

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

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

xml.Save(@"C:\xmlout.xml");

请注意,在上面的链接的代码是比较旧,而且很可能会清理使用位LINQ的,但它应该做的伎俩。

Note that the code at the link above is rather old, and probably could be cleaned up a bit using Linq, but it should do the trick.

这篇关于CSV转换为XML时,CSV包含字符和数字数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆