Dejan Biljecki
Dejan Biljecki

Reputation: 605

Parsing an XML element in javascript/jq

<action id="118" type="move" shipID="251" X="29" Y="0" rotate="90" />

I have been stuck too long on this - The above xml string is the whole ajax response I get, but I cannot parse the attributes. I keep getting either errors, or undefined or [object] [Object] and I have tried so many stuff...

Problem might be that I only have 1 tag with attributes...

Upvotes: 0

Views: 303

Answers (2)

ssilas777
ssilas777

Reputation: 9804

Use Jquery .parseXML()

var xml = '<action id="118" type="move" shipID="251" X="29" Y="0" rotate="90" />';
var doc = $.parseXML(xml );

var id = $(doc).find('action').attr('id');
var shipID = $(doc).find('shipID').attr('id');

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

//I separated these variables so that you can read it easily
var xml = '<action id="118" type="move" shipID="251" X="29" Y="0" rotate="90" />';
var $doc = $.parseXML(xml);
var $xml = $($doc);

//then
var id = $xml.find('action').attr('id');

Demo: Fiddle

If you are OK with html parsing of the string then

//I separated these variables so that you can read it easily
var xml = '<action id="118" type="move" shipID="251" X="29" Y="0" rotate="90" />';
var $xml = $(xml);

//then
var id = $xml.attr('id');

console.log(id)

Demo: Fiddle

Upvotes: 0

Related Questions