Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access xml text node in Jquery

Tags:

jquery

xml

Suppose I get the following XML structure:

<root>
<item>
 <item1>text1</item1>
 <item2>text2</item2>
 more text here
</item>
</root>

"more text here" is a text node that is at the same level as the other data nodes in the hierarchy but it does not seem to be accessible.

Is there a way of extracting the text node shown above using jQuery functions?

like image 985
safoo Avatar asked Jun 02 '09 02:06

safoo


3 Answers

I came up with the same solution:

  var xml = $("<root><item1>text1</item1><item2>text2</item2>more text here</root>");
  alert($(xml).contents().empty().end().text());
like image 69
Jose Basilio Avatar answered Sep 19 '22 10:09

Jose Basilio


Use the contents() function. For example, if you have an XML fragment like:

var root = $('<root><item1>text1</item1><item2>text2</item2>more text here</root>');

Then you can get at the text via:

var txt = root.contents()[2]

That is assuming that the text node is always the 3rd child of <root>. Otherwise, if you do not know the position, or may have a node that contains multiple text nodes, you should collect all of the text nodes by filtering:

var textList = root.contents().filter(function() { return this.nodeType == 3; });

This returns an array of text nodes that are found in the XML fragment. To get at the strings in the list, just access the array slice:

var txt = textList[0];
like image 32
johnvey Avatar answered Sep 22 '22 10:09

johnvey


So the solution I came up with is to delete the item1 and item2 nodes leaving only the text:

    $(responseXML).find('item').each(function(){
         var item1_text = $(this).find('item1').text();
         var item2_text = $(this).find('item2').text();

         $(this).contents().empty(); //removes the other nodes

         var extra_text = $(this).text();

    }
like image 28
safoo Avatar answered Sep 20 '22 10:09

safoo