Javascript XML - how to return a null value

0
<Root>
  <Child1>First Child Value</Child1>
  <Child2>
    <Age>Age1 Value</Age>
    <Age />
    <Name />
  </Child2>
  <Child3>3-1</Child3>
  <Child3>3-2</Child3>
  <Child4>4</Child4>
  <Child5>5</Child5>
  <Child6>6</Child6>
</Root>

<script>
  var xmlDoc = xml.responseXML;
  var x = xmlDoc.getElementsByTagName("Root");
  alert(y[0].getElementsByTagName("Age")[0].childNodes[0].nodeValue);
  alert(y[0].getElementsByTagName("Age")[1].childNodes[0].nodeValue);
<script>

I am trying to get a null value from "Root" > "Child2" > "Age[1]" but I get the message "0x800a138f - JavaScript runtime error: Unable to get property 'nodeValue' of undefined or null reference".

Does anyone know where I am going wrong with this?

javascript
xml

1 Answer

1

getElementsByTagName("Age")[1] gives you <Age />.

It has no child nodes so .childNodes[0] gives you null.

null.nodeValue is not allowed.


You need to test if y[0].getElementsByTagName("Age")[1].childNodes[0] is a true value before you try to read properties on it.

answered on Stack Overflow Jun 29, 2016 by Quentin

User contributions licensed under CC BY-SA 3.0