2013-08-30 164 views
1

我有一個從第三方例程返回的XML字符串。我希望能夠將這個XML字符串輸出到我的VB.NET程序中的.CSV文件中。有人可以提供一些建議,以最好的方式來做到這一點?將XML字符串轉換爲CSV?

感謝

+0

如果你想XML轉換爲CSV沒有一個直接轉換爲XML允許更多。並非所有的行都需要相同。可以有多個價值。 – Paparazzi

回答

2

試試這個:

' First read your XML string in 
Dim doc As XDocument = XDocument.Parse(xmlString) 

' Create a string builder to hold the output CSV 
Dim theOutput As New StringBuilder(1000) 

' Loop through the nodes of the XML 
For Each node As XElement In doc.Descendants("name of element you want to start at") 
    For Each innerNode As XElement In node.Elements() 
     theOutput.AppendFormat("{0},", innerNode.Attribute("data").Value) 
    Next 

    ' Remove trailing comma 
    theOutput.Remove(theOutput.Length - 1, 1) 
    theOutput.AppendLine() 
Next 

' Write output to file and do whatever you want the file here 
File.WriteAllText("path to file.csv", theOutput.ToString()) 
+0

昏暗的xmlString作爲字符串= 「一個兩」 昏暗DOC作爲的XDocument = XDocument.Parse(的xmlString) 昏暗theOutput作爲新的StringBuilder(1000) 對於每個節點的XElement在doc.Descendants(」 a) 對於每個innerNode作爲XElement在node.Elements() theOutput.AppendFormat(「{0}」,innerNode.Element(「b」)。Value) Next theOutput.Remove(theOutput.Length - 1 ,1) theOutput.AppendLine() Next –

+0

你得到了什麼錯誤? –