Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 88854

creating nested xml from excel

$
0
0

I am new to vbs and building a script to create nested xml from excel sheet. However, I ended up in creating a flat xml. First, I am trying to check the current row value with previous row value and adding as next line. but it is not showing. I am not sure where am I missing.

my code:

Sub xlsToxml()

Dim fso, oExcel, wb, ws
' create file system object
set fso = WScript.CreateObject("Scripting.Filesystemobject")
' create Excel application object
set oExcel = WScript.CreateObject("Excel.Application")
oExcel.Visible = True

' create xml file path
set XmlFile=fso.CreateTextFile("C:\Backup-44069411\C folder\Englobe\gsh.xml", True, True)

' creating xml file components
'XmlFile.Write("<?xml version=""1.0"" encoding=""utf-8""?>"&vbNewLine)
XmlFile.write("<Country>"&vbNewLine)

'reading contents from excel file
set wb = oExcel.Workbooks.Open("C:\Backup-44069411\C folder\Englobe\GSH\parent_child.xlsx")
set ws = wb.Sheets(1)

'getting the count of rows in the excel
Row_count = ws.UsedRange.Rows.Count
MsgBox Row_count

Parent = ws.cells(2,1).value ' Read the 1st column each row
Child = (ws.cells(2,2).value)' Read the 2nd column each row
XmlFile.write("<Parent>"&Parent&"</Parent>"&vbNewLine)
XmlFile.write("<Child>"&Child&"</Child>"&vbNewLine)

For i=3 To Row_count

    previous_parent = (ws.cells(i-1,1).value)
    previous_child = (ws.cells(i-1,2).value)    
    ' checking condition for previous values
    If ws.cells(i,1).value = ws.cells(i-1,2).value Then     
        XmlFile.write("<Parent>"&(ws.cells(i,1).value)&"</Parent>"&vbNewLine)   
        XmlFile.write("<Child>"&(ws.cells(i,2).value)&"</Child>"&vbNewLine)
    REM Else
        REM XmlFile.write("<Parent>"&Parent&"</Parent>"&vbNewLine)  
        REM XmlFile.write("<Child>"&Child&"</Child>"&vbNewLine)

    End If  

Next
XmlFile.write("</Country>"&vbNewLine)

wb.close ' closing the excel sheet that was opened
oExcel.Quit ' deleting excel object resources
MsgBox("Done")


End Sub

The output looks like this

enter image description here

but ideally, it should look like this..

enter image description here

suggestions would be really helpful and happy new year....

excel sheet data

enter image description here


Viewing all articles
Browse latest Browse all 88854

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>