.text() method in jQuery not working for xml element for some reason
I have the following javascript:
function getMessageFromXML(xml) {
alert('xml: ' + xml);
alert("Text of message: " + $(xml).find('dataModelResponse').find('adminMessage').text());
return $(xml).find('dataModelResponse').开发者_JS百科find('adminMessage').text();
}
which is being executed on the following XML:
<dataModelResponse>
<adminMessage>BARF</adminMessage>
<adminData>
<identifier>123456</identifier>
</adminData>
</dataModelResponse>
I know that the XML is correctly passed in, because of the first alert, but the message is showing up as blank for some reason. I verified that there were exactly 1 message and 1 dataModelResponse elements in the xml, using the .length modifier for similar find() queries, but for some reason, I can't get it to print out the correct message.
Suggestions?
EDIT: Changed the tag name I was searching for. Posted in between two revisions, sorry.
Replace $(xml).find('dataModelResponse').find('message').text();
with $(xml).find('message').text();
.
The documentation for jQuery.find()
states:
Get the descendants of each element in the current set of matched elements, filtered by a selector.
The root level element of your XML block is dataModelResponse
. By calling $(xml).find('dataModelResponse')
, you are essentially asking for a dataModelResponse
within your dataModelResponse
.
After $(xml)
you’re already on the root node, which is dataModelResponse
. Thus you will not find any child-elements of type dataModelResponse
, and thus text()
will return nothing.
Concrete:
console.log("Text of message: " + $(xml).text());
Will log
Text of message: BARF 123456
And (this is what you want)
console.log("Text of message: " + $(xml).find('message').text());
will log
Text of message: BARF
And
console.log("Text of message: " + $(xml).find('dataModelResponse').text());
will log
Text of message:
Should it be 'adminMessage'
instead?
If you are using jQuery 1.5, you can write:
alert("Text of message: " + $($.parseXML(xml)).find('adminMessage').text());
or
alert("Text of message: " + $($.parseXML(xml)).find('dataModelResponse > adminMessage').text());
or
alert("Text of message: " + $($.parseXML(xml)).find('dataModelResponse').find('adminMessage').text());
精彩评论