[英]Need to insert header row into csv when converting xml to CSV
構建一個通用的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();
}
String s=String.Join(",",doc.Descendants("fruit")
.Elements()
.Select(x=>x.Attribute("data").Value));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.