Extract XML file from a ZIP file

Asked

Viewed 176 times

-2

The code below makes a request to a Webservice that returns me an XML file inside a ZIP file.

myXMLText = ''
request({
    url: "http://webservice.newrastreamentoonline.com.br/",
    method: "POST",
    headers: {
        "content-type": "application/xml",  // <--Very important!!!
    },
    body: myXMLText
    }, function (error, response, body){
    //console.log(body);
})
.pipe(fs.createWriteStream('rastreamento.zip'))

Only instead of saving the file, I wanted to open it, take the XML file and go from parameter to another function that converts the XML into Json.

var result = convert.xml2js(xml,{alwaysChildren: true}); 

How can I take the file contents and save in the xml variable from the bottom function to make the conversation?

2 answers

0

One possible solution to this problem is not to save the file in the zip and do the direct conversion to json before creating the zip.

With the lib xml2json you can achieve the desired result. Using your code would be:

const parser = require('xml2json');
myXMLText = ''
request({
    url: "http://webservice.newrastreamentoonline.com.br/",
    method: "POST",
    headers: {
        "content-type": "application/xml",  // <--Very important!!!
    },
    body: myXMLText
    }, function (error, response, body){
        if (error) {
            console.log(error)
        }
        const myjson = parser.toJson(body);
        //console.log(myjson);
})

Notice that I did not make my code flow to transform the xml in zip. Placing the direct result inside the variable myjson.

-1


I did it "hard".

After downloading the file, unzipped, opened it, read the xml content.

It worked in the end.

request({
    url: "http://webservice.xxxxxxx.com.br/",
    method: "POST",
    headers: {
        "content-type": "application/xml",  // <--Very important!!!
    },
    body: myXMLText
    }, function (error, response, body){
    
    })
.pipe(fs.createWriteStream('onix.zip')) //salvo o arquivo zip
.on('finish',()=>{
    console.log('Arquivo baixado do WebService')
    fs.createReadStream('onix.zip')
    .pipe(unzipper.Parse())
    .on('entry', function (entry) {
      console.log('Descompactando arquivo')
      const fileName = entry.path;
      const type = entry.type; // 'Directory' or 'File'
      const size = entry.vars.uncompressedSize; // There is also compressedSize;
      console.log(fileName)
      entry.pipe(fs.createWriteStream('output/onix.xml')
                .on('error', err => console.log('error', err.message))
                .on('ready',()=>{
                    console.log('Lendo arquivo')
                    fs.createReadStream('output/onix.xml')
                    .on('data', function (chunk) { 
                        //console.log('aqui4')
                        xml+=chunk.toString()
                        //console.log(xml); 
                    })
                    .on('end', function (chunk) {
                        //console.log(xml) 
                        console.log('Convertendo de XML p/ JSON')
                        result = convert.xml2js(xml,{alwaysChildren: true}); // or convert.xml2json(xml, options)\
                        
                        console.log('Preparando SQL STATMENT | '+result.elements[0].elements.length+' LINHAS')
                        sql='';
                        for(i=0;i<result.elements[0].elements.length;i++){//trocar o 5 por result.elements[0].elements.length
                            table=''
                            value=''
                            for(j=0;j<result.elements[0].elements[i].elements.length;j++){
                                //sql += (result.elements[0].elements[i].elements[j].name);
                                //console.log(JSON.parse(result.elements[0].elements[i].elements[j].elements));                        
                                try{
                                    if(result.elements[0].elements[i].elements[j].name.toLowerCase()=='rod' || result.elements[0].elements[i].elements[j].elements[0].text==null){
                        
                                    }else{
                                        table += result.elements[0].elements[i].elements[j].name.toLowerCase()+(j==(result.elements[0].elements[i].elements.length-1)?'':',')
                                        value += "'"+result.elements[0].elements[i].elements[j].elements[0].text.replace('\'',' ').replace('true','1').replace('false','0')+"'"+(j==(result.elements[0].elements[i].elements.length-1)?'':',')
                                    }                                    
                                }catch{
                        
                                }
                            }
                            sql += 'INSERT INTO onixsat (' + table + ') VALUES (' + value + ')'
                            sql+=';\n'
                        }
                        console.log('Executando SQL')
                        //console.log(sql)
                        
                    })
                })
                
            )
    })
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.