E' bene precisare innanzitutto che non sempre e' possibile convertire un file XML in CSV (perche' i file XML possono avere anche una struttura gerarchica che non e' replicabile allo stesso modo su un CSV), in molti casi pero' puo' essere sufficiente replicare solo alcuni nodi un file XML su un file CSV, per effettuare semplici importazioni od elaborazioni
Lo script di esempio qui sotto, permette di elaborare un file XML simile al seguente:
e di convertirlo in un file CSV delimitato come questo:
Lo script di esempio qui sotto, permette di elaborare un file XML simile al seguente:
<?xml version="1.0" encoding="ISO-8859-1"?>
<Products>
<Product>
<Code>STAM0001</Code>
<Name>Stampante Epson Stylus Color</Name>
<Quantity>5</Quantity>
<Photo>http://www.miosito.com/foto1.jpg</Photo>
</Product>
<Product>
<Code>MON0001</Code>
<Name>Monitor Acer LCD 22"</Name>
<Quantity>3</Quantity>
<Photo>http://www.miosito.com/acer.jpg</Photo>
</Product>
</Products>
e di convertirlo in un file CSV delimitato come questo:
"STAM0001";@Stampante Epson Stylus Color";"5";"http://www.miosito.com/foto1.jpg"
"MON0001";"Monitor Acer LCD 22""";"3";"http://www.miosito.com/acer.jpg"
Questo lo script (ovviamente sara' da adattare in base alle proprie esigenze ed in base alla struttura del proprio file XML):
Option Explicit
Dim FileXML
Dim FileCSV
Dim ProdottoXML
Dim Prodotto
Set FileCSV=Rdy.BigString
Set FileXML = CreateObject("MSXML.DOMDocument")
FileXML.async = False
FileXML.setProperty "SelectionLanguage", "XPath"
FileXML.loadXML Rdy.LoadStringFromFile("C:\Elaborazioni\prodotti.xml")
If FileXML.parseError.errorCode = 0 Then
For Each ProdottoXML In FileXML.selectSingleNode("//Products").childNodes
Set Prodotto = CreateObject("MSXML.DOMDocument")
If Prodotto.loadXML( ProdottoXML.xml) Then
FileCSV.Add """" & Replace(Prodotto.selectSingleNode("//Code").Text,"""","""""") & """" & ";"
FileCSV.Add """" & Replace(Prodotto.selectSingleNode("//Name").Text,"""","""""") & """" & ";"
FileCSV.Add """" & Replace(Prodotto.selectSingleNode("//Quantity").Text,"""","""""") & """" & ";"
FileCSV.Add """" & Replace(Prodotto.selectSingleNode("//Photo").Text,"""","""""") & """"
FileCSV.Add vbCrLf
End If
Set Prodotto = Nothing
Next
Else
MsgBox "Errore parsing XML" & vbCrLf & "Linea " & FileXML.parseError.line & vbCrLf & "Reason : " & FileXML.parseError.reason
End If
Set FileXML = Nothing
Rdy.SaveStringToFile "C:\Elaborazioni\prodotti.csv",FileCSV.Value
Set FileCSV = Nothing