13

I am trying to parse and query for an element within an xml using xml2js. My xml string is as follows:

var xml = "<config><test>Hello</test><data>SomeData</data></config>";

What I want is to extract the value in and assign it to var extractedData

Here's what I have so far:

var parser = new xml2js.Parser();
parser.parseString(xml, function(err,result){
  //Extract the value from the data element
  extractedData = result['data'];
}

This does not work. Can somebody point out how I might be able to grab the values from my xml?

Thanks

This doesn't seem to be working. Can somebody tell me what might be the issue here?

sc_ray
  • 7,803
  • 11
  • 63
  • 100

1 Answers1

31

it works for me

var xml2js = require('xml2js');
var xml = "<config><test>Hello</test><data>SomeData</data></config>";

var extractedData = "";
var parser = new xml2js.Parser();
parser.parseString(xml, function(err,result){
  //Extract the value from the data element
  extractedData = result['config']['data'];
  console.log(extractedData);
});
console.log("Note that you can't use value here if parseString is async; extractedData=", extractedData);

result:

SomeData
Note that you can't use value here if parseString is async; extractedData= SomeData
Tom Himanen
  • 53
  • 1
  • 4
Andrey Sidorov
  • 24,905
  • 4
  • 62
  • 75
  • 3
    How can I print data which is in 5 or 6 level of depth – Vishwanath gowda k Oct 15 '15 at 09:50
  • @Vishwanathgowdak use `util.inspect()`; see the accepted answer here for a quick example: http://stackoverflow.com/questions/10729276/how-can-i-get-the-full-object-in-node-js-console-log-rather-than-object Here's a quick and dirty approach: `console.log(require('util').inspect(result, false, null));` – Josh1billion Mar 08 '16 at 20:43