【发布时间】:2019-10-31 17:41:07
【问题描述】:
如何将 csv 转换为 xml,其中 csv 中的每一列都是通过 C# 的 xml 标签中的属性? 让我告诉你我的意思: 这是 CSV:
1;A;a;b;c;d;
2;B;e;f;g;h;
这是 Xml:
<section>
<row code="1" s1="A">
<col code="5">a</col>
<col code="6">b</col>
<col code="7">c</col>
<col code="8">d</col>
</row>
<row code="2" s1="B">
<col code="5">e</col>
<col code="6">f</col>
<col code="7">g</col>
<col code="8">h</col>
</row>
</section>
其中“行代码”= 第一列,“s1”=2nd,“col 代码=5”=3rd,“col 代码=6”=第 4 列 ets。 这就是任务。
现在我有 xmlSchema 类,csv 类,但是我在映射 csv - xml 时遇到了一些问题。 这是 XMLSchema.cs 的一部分:
public partial class reportSectionsSectionRowCol
{
private string codeField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string code
{ get {return this.codeField;}
set {this.codeField = value;}
}
[System.Xml.Serialization.XmlTextAttribute()]
public string Value
{
get{return this.valueField;}
set{this.valueField = value;}
}
}
col - 具有属性代码和值的 XML 元素。
<row code="1" s1="A">
<col code="5">a</col>
<col code="6">b</col>
<col code="7">c</col>
<col code="8">d</col>
</row>
这是映射:
static void MappingCSVtoXML(report report, CSVData csvData)
{
if (csvData != null)
{
var col = new reportSectionsSectionRowCol[]{ new reportSectionsSectionRowCol(),
new reportSectionsSectionRowCol(),
new reportSectionsSectionRowCol(),
new reportSectionsSectionRowCol()};
var row = new reportSectionsSectionRow[2] { new reportSectionsSectionRow(), new reportSectionsSectionRow() };
for (int i = 0; i < 2; i++)
{
col[0].code = "5"; col[0].Value = csvData.rows[i].depreciationGroupNumber;
col[1].code = "6"; col[1].Value = csvData.rows[i].commissioningYear;
col[2].code = "7"; col[2].Value = csvData.rows[i].startYear;
col[3].code = "8"; col[3].Value = csvData.rows[i].ageAtLiquidation;
row[i].code = csvData.rows[i].okof.Substring(0, 3); // 1,2
row[i].col = col; // Reference type
row[i].s1 = csvData.rows[i].rowNumber; //A,B
}
report.sections = new reportSectionsSection[1]{new reportSectionsSection(){code = "1", row = row}};
}
}
问题在于 col 是引用类型,并且只记住最后一个值。 总体结果是
<section>
<row code="1" s1="A">
<col code="5">e</col>
<col code="6">f</col>
<col code="7">g</col>
<col code="8">h</col>
</row>
<row code="2" s1="B">
<col code="5">e</col>
<col code="6">f</col>
<col code="7">g</col>
<col code="8">h</col>
</row>
</section>
我该如何解决?
【问题讨论】:
-
我会构建一些数据类来表示 CSV 数据和 XML 数据的结构。然后使用 filehelpers.net 之类的库导入 CSV 数据,将其映射到 XML 数据类并使用 XML 序列化器将其导出。
-
@MindSwipe 对我来说,没有理由赞成或反对,但这只是我的意见,拥有一个 POV 绝对没问题。我欢迎你的评论,为什么你不投票:o)
-
@SirRufo 请检查下面的答案
-
如果您想回答问题,您应该只发布一个答案。如果您想为问题提供更多信息,请编辑问题。
-
@SirRufo 好的,我做到了
标签: c# xml csv converters