构建一个通用的 xml 到 csv 转换器作为一个项目来帮助学习 c#,并且正在寻找一种将标题行插入 CSV 的优雅方法。我可以在循环内手动构建它,就像我通过在节点名称后面附加逗号来附加 XML 数据值一样,但似乎应该有一种更有效的方法将 doc.Descendants 集合转换为逗号分隔的列表. 也许我也错误地添加了数据。我知道以这种方式构建字符串的 PHP 不是最佳的。
这是 XML 的示例:
<?xml version="1.0" ?>
<fruits>
<fruit>
<name data="watermelon" />
<size data="large" />
<color data="green" />
</fruit>
<fruit>
<name data="Strawberry" />
<size data="medium" />
<color data="red" />
</fruit>
</fruits>
这是代码:
//read the xml doc and remove BOM
string XML2Convert = System.IO.File.ReadAllText(@"C:\Websites\CSharp\Scripts\XML2CSVDocs\test.xml");
XML2Convert.Replace(((char)0xFEFF), '\0');
//parse into doc object
XDocument doc = XDocument.Parse(XML2Convert);
//create a new stringbuilder
StringBuilder sb = new StringBuilder(1000);
foreach (XElement node in doc.Descendants("fruit"))
{
foreach (XElement innerNode in node.Elements())
{
//need a better way here to build the header row in the CSV
//string headerRow = innerNode.Name + ",";
//add the xml data values to the line
//possibly a better way here also to add each value to the line
sb.AppendFormat("{0}", innerNode.Attribute("data").Value + ",");
}
//remove trailing comma before appending the data line
sb.Remove(sb.Length - 1, 1);
//add a line to the stringBuilder object
sb.AppendLine();
}