Vishal
Vishal

Reputation: 559

Not able to read XML Child node values in Java Script

I am not able to read child node values. below is the XML i am trying to read. i wanted to read value of each child node.

 <vir-analysis version="2.9">
    <vehicle>
    <registration>
    <first-registration-date>16-Aug-1988</first-registration-date>
    <registration-status>Active</registration-status>
    <cause-of-last-registration>New</cause-of-last-registration>
    <registered-overseas>No</registered-overseas>
    <last-registration-date>16-Aug-1988</last-registration-date>
    </registration>

    <licence>
    <expiry-date value="2016-02-13">13-Feb-2016</expiry-date>
    <licence-type code="L">Licence</licence-type>
    <issue-date value="2015-01-15">15-Jan-2015</issue-date>
    </licence>

    <wof>
    <last-inspection-date>24-Feb-2015</last-inspection-date>
    <last-inspection-result code="P">Pass</last-inspection-result>
    <expiry-date value="2015-08-24">24-Aug-2015</expiry-date>
    </wof>   

    <cof>
    <is-subject-to value="false">No</is-subject-to>
    <expiry-date value="2015-08-24">24-Aug-2015</expiry-date>
    </cof>

    </vir-analysis>

Sample code with which i am trying to read values is as below, i am getting null values

code:

if(xmlDoc.getElementsByTagName("licence").length!= 0){
    document.getElementById('LICENCE_EXPIRY_DATE').value =  xmlDoc.getElementsByTagName("licence")[0].childNodes[1].nodeValue;
    document.getElementById('LICENCE_TYPE').value = xmlDoc.getElementsByTagName("licence")[0].childNodes[2].nodeValue;  

Upvotes: 0

Views: 1099

Answers (1)

Mouser
Mouser

Reputation: 13304

You need to do this:

if(xmlDoc.getElementsByTagName("licence").length!= 0){
document.getElementById('LICENCE_EXPIRY_DATE').value =  xmlDoc.getElementsByTagName("licence")[0].childNodes[1].childNodes[0].nodeValue; //a extra childnode is added to select the text node and display its content.
document.getElementById('LICENCE_TYPE').value = xmlDoc.getElementsByTagName("licence")[0].childNodes[2].childNodes[0].nodeValue;

Or use textContent like this:

if(xmlDoc.getElementsByTagName("licence").length!= 0){
document.getElementById('LICENCE_EXPIRY_DATE').value =  xmlDoc.getElementsByTagName("licence")[0].childNodes[1].textContent;
document.getElementById('LICENCE_TYPE').value = xmlDoc.getElementsByTagName("licence")[0].childNodes[2].textContent;

nodeValue on an element will return null. However on a text node it will return the value. Since text is treated as a node you need to select another childnode. textContent gives you all the text inside the element.

Different node-types. Text inside a node is treated as a text-node. That's why nodeValue on the element returned null. Table from MDN

Upvotes: 1

Related Questions