1

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?

1
  • 1
    getElementsByTagName returns a collection - as you seem to realise with var x and forget in the very next line of code! Commented Nov 30, 2015 at 9:42

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I wasn't aware about querySelector. it is much simple than trying to use GetElements.
beware, it may not be universally available - though it has been in internet explorer since IE8, so, pretty safe to use (I know I know, there's still a big percentage of IE7 out there)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.