How to get each item of an XML?

Asked

Viewed 41 times

2

In my Node.js application, I have this answer in XML:

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<checkout>
    <code>meucode</code>
    <date>minhadate</date>
</checkout>

Which is in this variable:

var response;

How can I get the data that is on <code></code> and in <date></date> in Node.js?

1 answer

3

The simplest way, in my view, would be to use a library to do the parse XML for a Javascript/JSON object.

Could use the fast-xml-parser on Node.JS:

  • Installation
npm install fast-xml-parser
  • Use
const parser = require('fast-xml-parser');

const jsonObj = parser.parse(response); // "response" é a sua variável

Example using a CDN:

const xmlData =
  '<bookstore><book>' +
  '<title>Everyday Italian</title>' +
  '<author>Giada De Laurentiis</author>' +
  '<year>2005</year>' +
  '</book></bookstore>';
  
const jsonObj = parser.parse(xmlData);

console.log('XML em JSON:', jsonObj);

// Acessando as propriedades deste objeto:
console.log('"title" do xmlData: ', jsonObj.bookstore.book.title);

// simulando seu código
const response =
  '<checkout>' +
  '<code>meucode</code>' +
  '<date>minhadate</date>' +
  '</checkout>';

const responseObj = parser.parse(response);

console.log('dados do "response":', responseObj);
console.log('"code" do responseObj:', responseObj.checkout.code);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fast-xml-parser/3.18.0/parser.min.js"></script>

  • Thanks worked out.

Browser other questions tagged

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