Skip to content
Advertisement

How to get a certain line from xml from other webpage (url) in js?

const xhrRequest = new XMLHttpRequest();

xhrRequest.onload = function()
{
  dump(xhrRequest.responseXML.documentElement.nodeName);

  console.log(xhrRequest.responseXML.documentElement.nodeName);

  
  
}

xhrRequest.open("GET", "/website_url.xml")
xhrRequest.responseType = "document";
xhrRequest.send();

I’m trying to request a xml page from a page, but i’m unable to get certain line from xml in javascript. Thank you!

Advertisement

Answer

You can easily send requests to other pages with an AJAX http request found here: https://www.w3schools.com/js/js_ajax_intro.asp

Here is an example function:

function SendRequest(){
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if(this.readyState == 4 && this.status == 200){
            // Success
        }
    };
    xmlhttp.open("GET", "example.com", true);
    xmlhttp.send();
}

Now, about getting a value from the xml document, you can use .getElementsByTagName(). Notice that this is an array of elements so you have to append an index such as [0]
This would go inside the onreadystatechange of the http request

if(this.readyState == 4 && this.status == 200){
    let xmlDocument = this.responseXML;
    console.log(xmlDocument.getElementsByTagName("TestTag")[0].childNodes[0].nodeValue);
}

So if the xml document had an element like:

<TestTag>Hello</TestTag>

the function would print Hello

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement