Parse CSV file in VB Script

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • madankarmukta
    Contributor
    • Apr 2008
    • 308

    Parse CSV file in VB Script

    Hi All,

    I am trying to convert the CSV file to Xml file using VBScript.

    I tried the following -

    Code:
    dim fso, tso , xmlobj, tsoCopy,arrDestFileLines ,outputfile
    dim i
    dim RootElement,CUSTOMER,testnode
    
    set fso = CreateObject("Scripting.FileSystemObject")
    
    i = 0
    
    set xmlobj = CreateObject("Microsoft.XMLDOM")
    
    set tso = fso.OpenTextFile("D:\SomePath\Input_File.csv")
    
    set RootElement = xmlobj.CreateElement("REBATE")
    
    Do Until tso.AtEndOfStream
    
    arrDestFileLines = split(tso.ReadLine,",")
    
    REM Attempt to add only one node - just for testing
    
    if i = 0 Then
    
    set CUSTOMER = xmlobj.CreateElement("CUSTOMER")
    
    set testnode = xmlobj.CreateTextNode ("John")
    
    CUSTOMER.appendchild(testnode)
    
    RootElement.appendChild(CUSTOMER)
    
    i = i + 1
    
    end if
    
    Loop
    
    xmlobj.Save "D:\SomePath\OutputFile.xml"
    The attempt is to create the N xml nodes if the CSV file contains N columns.
    In the above code snap I just tried to create a single node IN XML FILE.When I tried running that script found that the xml file contains nothing.Moreove r the script is running successfully.

    I am not able to troubleshoot the problem. Why created xml document is blank ..?

    Thanks!
  • Delerna
    Recognized Expert Top Contributor
    • Jan 2008
    • 1134

    #2
    you did not append each child after creating it (see bold additions)
    [code=vba]
    dim fso, tso , xmlobj, tsoCopy,arrDest FileLines ,outputfile
    dim i
    dim RootElement,CUS TOMER,testnode
    set fso = CreateObject("S cripting.FileSy stemObject")
    i = 0
    set xmlobj = CreateObject("M icrosoft.XMLDOM ")
    set tso = fso.OpenTextFil e("Input_File.c sv")
    set RootElement = xmlobj.CreateEl ement("REBATE")
    xmlobj.appendCh ild(RootElement )

    Do Until tso.AtEndOfStre am
    arrDestFileLine s = split(tso.ReadL ine,",")
    if i = 0 Then
    set CUSTOMER = xmlobj.CreateEl ement("CUSTOMER ")
    RootElement.app endChild(Custom er)
    set testnode = xmlobj.CreateTe xtNode ("John")
    CUSTOMER.append child(testnode)
    Set objCurrNode = xmlobj.document Element
    i = i + 1
    end if
    Loop

    xmlobj.Save "OutputFile.xml "

    [/code]

    You created all the elements OK , but they never got appended to the xmlobj.
    Therefore when you saved it it was empty because nothing was added to it.

    Comment

    • madankarmukta
      Contributor
      • Apr 2008
      • 308

      #3
      Thanks Delerna!

      I tried your suggestion.. and it ran as expected..

      Thanks again!

      Comment

      Working...