5

How do you fetch an xml from online with node.js and parse it into a javascript object? I've been searching the npm register but only found how to parse the xml-string, not how to fetch it.

2
  • 1
    Look up how to download files (any files, not just XML). There isn't a library specifically for downloading XML because there's nothing special about XML files in that regard. Commented Oct 5, 2013 at 7:30
  • Ok. So I should download it, the parse it? Because with rss and feedparser i could just parse it by inputting an url Commented Oct 5, 2013 at 7:32

3 Answers 3

6

To fetch an online resource, you can use http.get(). The data can be loaded into memory, or directly sent to a XML parser since some support the feature of parsing streams.

var req = http.get(url, function(res) {
  // save the data
  var xml = '';
  res.on('data', function(chunk) {
    xml += chunk;
  });

  res.on('end', function() {
    // parse xml
  });

  // or you can pipe the data to a parser
  res.pipe(dest);
});

req.on('error', function(err) {
  // debug error
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! It all starts to make sense now. =D
Don't forget that you need to include this line first: var http = require('http');
0

This should work too.

const request = require("request-promise");

const web_url = "https://www.gillmanacura.com/sitemap.xml";

(async() => {
    let emptyData = [];   
        let resp = await request({
            uri: web_url,
            headers:{},
            timeout:10000,
            json: true,
            gzip: true
        });        
        console.log(resp)       
})();

Comments

0

Using node-fetch

Here an example using node-fetch retrieving xml.

Install a lower version of node-fetch to use require or else use regular ESM import.

npm install node-fetch@^2.6.6

const fetch = require('node-fetch');
const xml_to_js = require('xml-js');//npm i xml-js

var query = "https://api.dreamstime.com/api.xml?username="+usernamer+"&password="+api_key+"&type=get&request=search&srh_field="+term;
        
    fetch(query, {
        method: 'GET',
        headers: {
        'Content-Type': 'text/xml',
        'User-Agent': '*'
        },
        }).then(function(response){ return response.text(); })
        .then(function(xml) {
        
        //convert to workable json
        var json_result = xml_to_js.xml2json(xml, {compact: true, spaces: 4});

        console.log(json_result);//json
        
        
        })
        .catch((error) => {
        console.error('Error:', error);
        
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.