Erel Segal-Halevi
Erel Segal-Halevi

Reputation: 36793

Cannot get the attr after parseXml

I wrote this simple JQuery code, to find an attribute of some XML code:

<html>
<head>
<meta charset='utf-8' />
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
<script>
var msg = '<utility value="346" cost="0" />';
alert(msg);
var xmlInput = $.parseXML(msg);
alert(xmlInput);
var xmlObject = $(xmlInput);
alert(xmlObject);
var tagname = xmlObject.nodeName;
alert("tagname="+tagname);
var value = xmlObject.attr("value");
alert("value="+tagname);
</script>
</body></html>

However, it doesn't work: http://irsrv2.cs.biu.ac.il:8080/GeniusWeb/jqueryTest3.html

The tag name and the value are "undefined", I checked on Firefox and Chrome.

How can I fix this?

Upvotes: 0

Views: 89

Answers (2)

Palpatim
Palpatim

Reputation: 9272

Two problems. First, your posted code's last alert is alert("value="+tagname);`, which isn't going to give you what you want in any case. Second, you need to retrieve the element from the parsed XML jQuery set:

var msg = '<utility value="346" cost="0" />';
alert(msg);
var xmlInput = $.parseXML(msg);
alert(xmlInput);
var xmlObject = $(xmlInput);
alert(xmlObject);
var utility = xmlObject.find("utility");
alert("utility="+utility);
var value = utility.attr("value");
alert("value="+value);​

Upvotes: 1

VisioN
VisioN

Reputation: 145428

You should search for certain element in xmlObject, since XML 'starts' with the root element.

var tagname = xmlInput.firstChild.nodeName;
// or xmlObject.children().get(0).nodeName

var value = $("utility", xmlObject).attr("value");

Upvotes: 1

Related Questions