Ram
Ram

Reputation: 1054

Convert XML to Object using jQuery of plain javascript

Here is a sample XML:

<xml id="javascriptObject">
  <name>Joe</name>
  <age>12</age>
  <gender>M</gender>
</xml>

Object produced after digesting the XML above should be equivalent to:

var obj = {name: 'Joe', age: '12', gender: 'M'};

You guys know any functions in javascript or in jQuery that will convert the XML to a javascript object? If none, any ideas on how to do this the best way as possible? Thanks guys!

Upvotes: 2

Views: 10267

Answers (2)

Drupars
Drupars

Reputation: 13

you can use this project ;) this allows you to convert between json objects and XML objects

Upvotes: 0

palaѕн
palaѕн

Reputation: 73896

Try this, using the parseXML() method:

var xml = '<xml id="javascriptObject"><name>Joe</name><age>12</age><gender>M</gender></xml>',
    xmlDoc = $.parseXML(xml),
    $xml = $(xmlDoc);

var obj = {
    name: $xml.find('name').text(),
    age: $xml.find('age').text(),
    gender: $xml.find('gender').text()
};

console.log(obj);

Upvotes: 2

Related Questions