0

How do I parse whatever is inside 'value' tag from below XML to an array in nodejs ? I tried npm xpath/xmldom, XMLExtract then xml2json but without success yet.

<response status="success"><result>
  <resource-monitor>
    <data-processors>
      <dp0>
        <second>
          <cpu-load-average>
            <entry>
              <coreid>0</coreid>
              <value>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</value>
            </entry>
            <entry>
              <coreid>1</coreid>
              <value>2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2</value>
            </entry>

2 Answers 2

1

One option is to use cheerio like this:

var cheerio = require('cheerio');
var _ = require('lodash');

var $ = cheerio.load('<cpu-load-average>\
        <entry>\
          <coreid>0</coreid>\
          <value>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</value>\
        </entry>\
        <entry>\
          <coreid>1</coreid>\
          <value>2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2</value>\
        </entry>\
    </cpu-load-average>', 
    { xmlMode: true }
);

var values = _.map($('cpu-load-average').find('value'), function(item) {
    return $(item).text().split(',');
});

console.log(values);

Try it on requirebin. If it is a big XML file cheerio should be faster than xml2js.

Sign up to request clarification or add additional context in comments.

Comments

1

You can convert the xml to json using xml2js and then spliting the value of the value tag using string split operation will produce an array of values.

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.