0

I'm trying to parse XML with Node.js and xml2js. In the documentation is says that $ is the character to access attributes. It doesn't seem to be working in my case.

The object result.ApiResponse.CommandResponse works fine. But anything I put afterwards is undefined.

Here's my code, it says $ is undefined :

var xml2js = require('xml2js');
var util = require('util');

var parser = new xml2js.Parser();
var xml = '<ApiResponse Status="OK"><Errors/><Warnings/><RequestedCommand>namecheap.domains.check</RequestedCommand><CommandResponse Type="namecheap.domains.check"><DomainCheckResult Domain="us.xyz" Available="true" ErrorNo="0" Description="" IsPremiumName="true" PremiumRegistrationPrice="13000.0000" PremiumRenewalPrice="13000.0000" PremiumRestorePrice="65.0000" PremiumTransferPrice="13000.0000" IcannFee="0.0000" EapFee="0.0000"/></CommandResponse><Server>PHX01APIEXT01</Server><GMTTimeDifference>--5:00</GMTTimeDifference><ExecutionTime>4.516</ExecutionTime></ApiResponse>';

parser.parseString(xml, function (err, result) {

console.log(util.inspect(result.ApiResponse.CommandResponse.DomainCheckResult.$.Available, false, null))    

});

Here's the console.log(result):

{ ApiResponse: 
   { '$': { Status: 'OK' },
     Errors: [ '' ],
     Warnings: [ '' ],
     RequestedCommand: [ 'namecheap.domains.check' ],
     CommandResponse: 
      [ { '$': { Type: 'namecheap.domains.check' },
          DomainCheckResult: 
           [ { '$': 
                { Domain: 'us.xyz',
                  Available: 'true',
                  ErrorNo: '0',
                  Description: '',
                  IsPremiumName: 'true',
                  PremiumRegistrationPrice: '13000.0000',
                  PremiumRenewalPrice: '13000.0000',
                  PremiumRestorePrice: '65.0000',
                  PremiumTransferPrice: '13000.0000',
                  IcannFee: '0.0000',
                  EapFee: '0.0000' } } ] } ],
     Server: [ 'PHX01APIEXT01' ],
     GMTTimeDifference: [ '--5:00' ],
     ExecutionTime: [ '4.516' ] } }

1 Answer 1

2

It looks like CommandResponse and DomainCheckResult are actually arrays, so you need to access their first elements using [0] before digging deeper into your data.

console.log(util.inspect(
    result.ApiResponse.CommandResponse[0].DomainCheckResult[0].$.Available,
    false, null
))
Sign up to request clarification or add additional context in comments.

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.