Request to external XML files

2

I work in NodeJs , I started using an API for anime / manga search , but unlike other APIs that I used, it was not available in > JSON , only in XML .

The format it has is the following:

<?xml version="1.0" encoding="utf-8"?>
<anime>
  <entry>
    <id>2889</id>
    <title>Bleach - The DiamondDust Rebellion</title>
    <english>Bleach: Diamond Dust Rebellion</english>
    <synonyms>Bleach: The Diamond Dust Rebellion - M&Aring; 
    Bleach - The DiamondDust Rebellion - Mou Hitotsu no Hyourinmaru</synonyms>
    <episodes>1</episodes>
    <type>Movie</type>
    <status>Finished Airing</status>
    <start_date>2007-12-22</start_date>
    <end_date>2007-12-22</end_date>
    <synopsis>A valuable artifact known as &amp;quot;King's Seal&amp;quot; is stolen...
    Meanwhile, a rogue Hitsugaya searches... (from ANN)</synopsis>
    <image>https://myanimelist.cdn-dena.com/images/anime/6/4052.jpg</image>
  </entry>
</anime>

How should I use it and what variables (or packages) should I use to get all the data from a file like this?

    
asked by Antonio Roman 13.01.2017 в 00:07
source

1 answer

2

One option is xml2js . This library converts an xml string into a javascript object but in the form of a string. You only need to use JSON.parse to have the xml in object.

parseString(xml, function (err, result) {
    console.log(result);
});

You can see your code in operation with this library here .

Another library is xml2json which is a parser between XML and JSON (both ways).

const parser = require('xml2json');

fetch ('...')
  .then(res => res.text())
  .then(xml => parser.toJson(xml, { object: true }))
  .then(anime => {
    // hacer algo
  });

The object parameter indicates whether you want to receive a objeto JavaScript instead of a JSON string.

Note: There is a bug with this library and it sometimes identifies entities in a wrong way (it does not usually happen much). For example, this word: M&Aring will be interpreted as HTML entity and the parser will fail when trying to convert it to unicode character.

You can find more here .

    
answered by 13.01.2017 / 00:42
source