2013-10-10 38 views
0

構建一個通用xml到csv轉換器作爲項目以幫助學習c#,並且正在尋找一種將標題行插入到CSV中的優雅方法。我可以在循環中手動構建它,就像我通過用逗號附加節點名稱附加XML數據值的方式一樣,但似乎應該有一種更有效的方法將doc.Descendants集合轉換爲逗號分隔列表。也許我錯誤地添加了數據。我知道用PHP以這種方式構建字符串並不理想。將xml轉換爲CSV時,需要將標題行插入到csv中

這裏是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(); 
} 

回答

0
String s=String.Join(",",doc.Descendants("fruit") 
          .Elements() 
          .Select(x=>x.Attribute("data").Value)); 
+0

我現在遇到的問題是,我結束了這樣一個字符串:西瓜,大,綠色,草莓,中等,紅色,我需要打破每一套子孫(「水果」)的下一行 – sarasotacoder

+0

我明白了:String s = String.Join(「,」,node。 Elements()。Select(x => x.Attribute(「data」)。Value));非常感謝您的幫助 – sarasotacoder

+0

@sarasotacoder如果有幫助..plz接受答案。 – Anirudha