Csv到XML,数组字符串有问题



大家好,我想转换我的CSV文件(路径)在XML文件(savepath)。在CSV文件中有13个header元素,我把它们都放在一个数组字符串中。我的问题是:我想在XML文件中只放入数组的1、2、3、10、11、12元素。我该怎么做呢?通过跳过,我只跳过第一个元素,但是我如何跳过中间的元素呢?非常感谢!!

var lines = File.ReadAllLines(path);
string[] headers;
headers = new string[13] {"PlantNo", "No", "Name", "cod_fatt", "tags_grp", "dos_type", "pervuoti", "cemq_chk", "rapp_ac", "code_01", "unit_01", "peso_01",""};
for (int i = 0; i < headers.Length; i ++)
{
lunghezza = i;
}
var xml = new XElement("DC8_Recipes",
lines.Where((line, lunghezza) => lunghezza > 0).Select(line => new XElement("DC8_Recipes",
line.Split(';').Skip(1).Select((column, lunghezza) => new XAttribute(headers[lunghezza], column)))));
xml.Save(savepath);

您可以使用LINQWhere()方法和索引枚举来排除特定的索引:

line.Split(';').Where((v, i) => !(i < 1 || (i > 4 && i < 10)))
// or 
var exclude = new int[] { 0, 5, 6, 7, 8, 9 };
line.Split(';').Where((v, i) => !exclude.Contains(i));
// or
var include = new int[] { 1, 2, 3, 4, 10, 11, 12 };
line.Split(';').Where((v, i) => include.Contains(i));

如果您有大量显式排除/包含,您可能希望将它们存储在具有更快搜索的数据类型中(例如。HashSet<int>),但对于<13个索引,这应该没问题。

我认为,你需要这样的东西:

using System.IO;
using System.Xml.Linq;
namespace CsvToXml
{
class Program
{
static void Main(string[] args)
{
const string csvFilePath = "C:\Temp\1.csv";
const string xmlFilePath = "C:\Temp\1.xml";
var indices = new int[] { 1, 2, 3, 10, 11, 12 };
var headers = new string[] { "PlantNo", "No", "Name", "cod_fatt", "tags_grp", 
"dos_type", "pervuoti", "cemq_chk", "rapp_ac", "code_01", 
"unit_01", "peso_01", "not_empty_attribute_name" };
var xItems = new XElement("items");
var xDocument = new XDocument(xItems);
var lines = File.ReadAllLines(csvFilePath);
foreach (var line in lines)
{
var xItem = new XElement("item");
var csvItems = line.Split(';');
foreach (var index in indices)
xItem.Add(new XAttribute(headers[index], csvItems[index]));
xItems.Add(xItem);
}
xDocument.Save(xmlFilePath);
}
}
}

输入文件"C:Temp1.csv"是:

0;+1;+2;+3;+4;+5;+6;+7;+8;+9;+10;+12;+13
0;-1;-2;-3;-4;-5;-6;-7;-8;-9;-10;-12;+13

输出文件"C:Temp1.xml"是:

<?xml version="1.0" encoding="utf-8"?>
<items>
<item No="+1" Name="+2" cod_fatt="+3" unit_01="+10" peso_01="+12" not_empty_attribute_name="+13" />
<item No="-1" Name="-2" cod_fatt="-3" unit_01="-10" peso_01="-12" not_empty_attribute_name="+13" />
</items>

如果你想使用linq:

var indices = new int[] { 1, 2, 3, 10, 11, 12 };
var xAttributes = indices.Select(x => new XAttribute(headers[x], csvItems[x]));