Benjamin
Benjamin

Reputation: 3826

accessing value of XML file in javascript

I load an XML document using XMLHTTPRequest in my js file as below:

<?xml version="1.0" encoding="utf-8"?>
<RMFSFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Host>www.example.com</Host>
<Port>8888</Port>   
<Uri>www.example.com</Uri>
<Path>
    <HD>
        <UNC>path1</UNC>
    </HD>
    <SD>
        <UNC>path2</UNC>
    </SD>
</Path>

I am trying to SELECT the value of "UNC" for HD using javascript.

I have tried something like below, which didn't work:

      var x = xml.getElementsByTagName('Path')[0];
      var y = x.getElementsByTagName('HD');
      var z = y.getElementsByTagName('UNC');

Any idea How Can I retrieve the Path?

Upvotes: 1

Views: 76

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

You're using getElementsByTagName correctly in the first line, then incorrectly after that

It should be

  var x = xml.getElementsByTagName('Path')[0];
  var y = x.getElementsByTagName('HD')[0];
  var z = y.getElementsByTagName('UNC')[0];

or, more simply (if you know there will only ever be one)

var z = xml.querySelector('Path>HD>UNC');

or, to get the first of "many"

var z = xml.querySelectorAll('Path>HD>UNC')[0];

I've ignored the fact that your XML is invalid, by the way, I figure that's a missed line when posting here

Upvotes: 2

Related Questions