大家好,我想將我的 CSV 檔案(路徑)轉換為 XML 檔案(保存路徑)。在 CSV 檔案中有 13 個標題元素,我將所有元素都放在一個陣列字串中。我的問題是:我只想在 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);
uj5u.com熱心網友回復:
您可以使用Where()帶有索引列舉的 LINQ方法來排除特定索引:
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 個索引,這應該沒問題。
uj5u.com熱心網友回復:
我想,你需要這樣的東西:
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:\Temp\1.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:\Temp\1.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]));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317695.html
