我编写了一个从Vlax代码片段派生的类。此外,我提供了一个单元测试来记录工作流程。
单元测试:
[TestMethod]
public void convert_csv_to_xml()
{
// Setup
var csvPath = @"Testware\vendor.csv";
var xmlPath = @"Testware\vendor.xml";
// Test
var success = DocumentConverter.Instance.CsvToXml(csvPath, xmlPath);
// Verify
var expected = File.Exists(xmlPath) && success;
Assert.AreEqual(true, expected);
}
CSV转XML:
public class DocumentConverter
{
#region Singleton
static DocumentConverter _documentConverter = null;
private DocumentConverter() { }
public static DocumentConverter Instance
{
get
{
if (_documentConverter == null)
{
_documentConverter = new DocumentConverter();
}
return _documentConverter;
}
}
#endregion
public bool CsvToXml(string sourcePath, string destinationPath)
{
var success = false;
var fileExists = File.Exists(sourcePath);
if (!fileExists)
{
return success;
}
var formatedLines = LoadCsv(sourcePath);
var headers = formatedLines[0].Split(',').Select(x => x.Trim('\"').Replace(" ", string.Empty)).ToArray();
var xml = new XElement("VendorParts",
formatedLines.Where((line, index) => index > 0).
Select(line => new XElement("Part",
line.Split(',').Select((field, index) => new XElement(headers[index], field)))));
try
{
xml.Save(destinationPath);
success = true;
}
catch (Exception ex)
{
success = false;
var baseException = ex.GetBaseException();
Debug.Write(baseException.Message);
}
return success;
}
private List<string> LoadCsv(string sourcePath)
{
var lines = File.ReadAllLines(sourcePath).ToList();
var formatedLines = new List<string>();
foreach (var line in lines)
{
var formatedLine = line.TrimEnd(',');
formatedLines.Add(formatedLine);
}
return formatedLines;
}
}
注意:
我通过删除每个CSV行条目的尾随逗号来扩展了Vlax的解决方案,这导致一个运行时异常,因为与列标题相关的索引超出了范围。
"A;B"
作为单个元素 - Meer<Column0 D =d />
而不是<Column0>D</Column0>
。非常感谢您的帮助。尝试查找并发现这似乎是最佳解决方案,但需要弄清楚如何使其自闭合。 - Jay