3

To better understand the difference between textConent and nodeValue I'd like to find out why using nodeValue in my code is not working. I have the following XML string which gets loaded through AJAX via a jQuery callback. If you look at the center of the loop, that section will produce a null value if I use nodeValue in place of textContent.

XML

<?xml version="1.0" encoding="UTF-8"?>
    <Sensors>
        <Sensor>
            <id>56</id>
            <state>false</state>
        </Sensor>
    </Sensors>

I use this function below to parse the XML.

JavaScript

  function parseSensors(data,status,xhr) {
         var xml = xhr.responseXML;
         var sensors = xml.documentElement.childNodes;

         var list="<ul>";             
         for(var i=0; i < sensors.length; i++) {
             list= list +"<li>"+sensors[i].childNodes[0].textContent+"</li>";                 
         }
         list=list+"</u>";
         document.getElementById("real-time_active_sensors").innerHTML=list;            
     }
1

1 Answer 1

1

The text portion of a node is actually a child of the node itself. If a node has no data in it, such as then a call to childNodes[0].nodeValue will fail. You need to check for how many childNodes are actually present before you attempt to access them. Otherwise you'll need to enforce a protocol that demands that when XML data is created it cannot contain empty tags.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.