Sagarmichael
Sagarmichael

Reputation: 1624

Javascript and xml parsing

I have a XML object and I am wanting to return the text value on the node which may have a number of child nodes.

  <binding name="s"><bnode>b1fff4d00000000fe</bnode></binding>
  <binding name="p"><uri>http://cidoc-crm.org/P1F.is_identified_by</uri></binding>
  <binding name="zebra"><literal>copper</literal></binding>

In the above case i am wanting to return the text in each node were I can specify the name value of the binding.

pseudo code: get text where binding name value == "s" ;

I have tried this

x[i].getElementsByTagName("binding")[0].childNodes[0].nodeValue

so it shouldn't matter what the child node name is in this case bnode.

I hope thats clear

Thanks.

Upvotes: 0

Views: 127

Answers (2)

Tim Down
Tim Down

Reputation: 324477

Easiest way to get the text content would be

x[i].getElementsByTagName("binding")[0].textContent;

However, textContent is unsupported in IE < 9, so you will need to navigate through to the text node in those browsers:

x[i].getElementsByTagName("binding")[0].firstChild.firstChild.data;

Demo: http://jsfiddle.net/p2SrZ/

Upvotes: 2

Joseph Marikle
Joseph Marikle

Reputation: 78520

You are trying to get the nodeValue of an element which will always result in null.[1] What you want is the nodeValue of the contained text node. Therefore, you have to unfortunately add another tier to this statement and your statement becomes

x[i].getElementsByTagName("binding")[0].childNodes[0].childNodes[0].nodeValue;

This will pull the text node value of the inner elements.

[1] Fake citation just click the link dang it.

Upvotes: 1

Related Questions