简体   繁体   中英

XML, Javascript - Uncaught TypeError: Cannot call method 'getElementsByTagName' of null

I am trying to create a table taking an HTML table from within a XML file. However, it keeps giving me the error Uncaught TypeError: Cannot call method 'getElementsByTagName' of null even though there definitely is a tag named <x> in the XML file. There is probably a glaringly obvious thing that is causing the problem, but this is the first time I have used XML and JS, so I'm not sure what it it is. Does anyone know what the problem is?

JS:

xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","media.xml",false);
xmlDoc=xmlhttp.responseXML; 

document.getElementById("y").innerHTML = xmlDoc.getElementsByTagName("x")[0];

XML:

<?xml version="1.0" encoding="UTF-8"?>
<library>
    <x>
        <![CDATA[
        <tr>
            <td>First cell</TD>
            <td>Second Cell</td>
            <td>Third cell</td>
        </tr>
        ]]>
    </x>
</library>

You have to parse your XML. Without parsing you can't access the nodes in the response string.

xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","media.xml",false);
xmlDoc=xmlhttp.responseXML;

parser = new DOMParser(); // new Parser
xmlDoc = parser.parseFromString(xmlDoc,"text/xml"); // Parse string

document.getElementById("y").innerHTML = xmlDoc.getElementsByTagName("x")[0].textContent || xmlDoc.getElementsByTagName("x")[0].innerText; // Use textContent for getting the content of the "x" node. In IE you have to use "innerText"

DOMParser

DOMParser can parse XML or HTML source stored in a string into a DOM Document.

JSfiddle

Please check the XML file which you have created. Your code looks good. It is not able to open and read the file properly.

Arun

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM