Thursday 15 September 2011

javascript - testing to see if you have empty text node in xml -


Using Ajax to fetch XML data Questions about blank text nodes

I asked this question Read / answered here

And it helped me to understand how structure is established, but I still have a question or two .. When he mentions this part:

"Carriage return and text node with some spaces or tabs"

How do you test to see if you Have you put an empty text node? I have tried to test to see:

  if nodeValue == zero nodeValue == "null" nodeValue == "" nodeValue == ""   

None of these works

I thought the length would probably be 0, so I did the test. Length and it returned 5 (1 return key and 4 tabs) .. added an extra tab there and tested again it returned 6)

Then I made a mistake how to remove whotspace and use it To be done:

  .replace (/ \ s + / g, ''); .replace (/ ^ \ s + | \ s + $ / g, '');   

Neither worked nor said. The length is still 5

The reason I want to test for this is because if I name each of the element nodes in the name before or exactly how the DOM is set up.

Or is there any better result to check whether the text node is just a tabs / space / return key, without a better way of navigating?

.replace (/ ^ \ s + | \ s + $ / g, '' ); works as long as the spaces / tabs are not actually spaces and tabs, but one of the various Unicode space-like characters. So I'm guessing that you were not using it correctly.

How will it use it:

  if (! TextNode.nodeValue.replace (/ ^ \ S + | \ ++ / $ + g, '')) { // node is empty}   

Example: |

  var xml = parseXml ("Exam & gt; \ n \ t \ t \ t & lt; / test & gt;"); Var textNode = xml.documentElement.firstChild; Display ("textNode.nodeValue.length =" + textNode.nodeValue.length); Display ('empty'? '+ ((TextNode.NodeAvailability.Relestes (/ ^ \ s + | \ s + $ / g,' '))); Function display (msg) {var p = document.create element ('p'); P.innerHTML = String (msg); Document.body.appendChild (P); }   

Output:

 textNode.nodeValue.length = 4 Is "empty"? << P>  > Replace  (although the exaggeration of doing this is trivial). In this way a test will do this:  
  if (/^\s*$/.test(textNode.nodeValue)) {// node "empty"}   

This regular expression (zero or more white space characters with both anchors) only matches that string which is already empty or is only included in white space characters.

No comments:

Post a Comment