Ann Sanderson
Ann Sanderson

Reputation: 211

Convert XML String To CSV?

I have an XML string that comes back from a 3rd party routine. I would like to be able to output this XML string into a .CSV file in my VB.NET program. Can someone offer some advice on the best way to do this?

Thanks

Upvotes: 1

Views: 4418

Answers (1)

Karl Anderson
Karl Anderson

Reputation: 34844

Try this:

' 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())

Upvotes: 2

Related Questions