0

I want to getElementsByTagName in xml file. It is my code(.html).

<html>
    <header>
        <title>Read XML</title>
    </header>
    <body>
        <h1>Hello My Application</h1>
        <script type="text/javascript">
        function readXML()
        {
            var xml= new XMLHttpRequest();
            xml.open('GET', 'C:\Users\xxx\Testxml.xml');
            //xml.send();
            var xmlData = xml.responseText;
            if(!xmlData)
            {
                xmlData = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
                var emp = xmlData.getElementsByTagName("employee");
                var name= emp[0].getElementsByTagName("name")[0].firstChild.data;
                document.write("Name = " + name);
            }
        }
        </script>
        <button onclick="readXML()">Read XML File</button>
    </body>
</html>

I run filename.html but there is error on line var name= emp[0].getElementsByTagName("name")[0].firstChild.data;

It is my xml file.

<company>
    <employee>
        <name>Chrish</name>
        <age>40</age>
        <salary>100</salary>
    </employee>
</company>

Could you help me please?

Error

Yogesh
  • 699
  • 1
  • 6
  • 21
Bell Aimsaard
  • 483
  • 3
  • 5
  • 16

1 Answers1

0

Have you tried logging your xmlData variable to see if you are actually able to read the xml file? Because, as far as I know, reading local xml files in javascript is not allowed directly. You can try reading it through the File API. Read more about it here.

And secondly, your if condition seems incorrect. You are checking for (!xmlData) which means it will run when xmlData is empty while it should be running when you are actually able to get data in xmlData variable.

codeslayer1
  • 3,666
  • 3
  • 17
  • 13