How to get access XML file from Javascript (two ways and every thing bug )

— I try everything on internet and nothing work (Only vanilla CSS + XML + XSL) —

I am try to get access XML value from javaScript but it doesn’t work

First time I try to do it
https://www.w3schools.com/xml/xsl_client.asp

<script>
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
  {
  xhttp = new ActiveXObject("Msxml2.XMLHTTP");
  }
else
  {
  xhttp = new XMLHttpRequest();
  }
xhttp.open("GET", filename, false);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
return xhttp.responseXML;
}

function displayResult()
{
xml = loadXMLDoc("cdcatalog.xml");
xsl = loadXMLDoc("cdcatalog.xsl");
// code for IE
if (window.ActiveXObject || xhttp.responseType == "msxml-document")
  {
  ex = xml.transformNode(xsl);
  document.getElementById("example").innerHTML = ex;
  }
// code for Chrome, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
  {
  xsltProcessor = new XSLTProcessor();
  xsltProcessor.importStylesheet(xsl);
  resultDocument = xsltProcessor.transformToFragment(xml, document);
  document.getElementById("example").appendChild(resultDocument);
  }
}
</script>

And have error on that – xhttp.open("GET", filename, false); line.
Another way I am try do from this video https://www.youtube.com/watch?v=0gON4MUdJE8 with Loading XML Data Using Fetch, and he tell me SCRIPT1002: Syntax error on first line for example fetch('./Albums.xml').then(() => 2)

I share some code I hope you can help me fix that issue, only try to get value on javascript.

ok my XML

<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="sheet.xsl"?>
<xmlTag>
blah blah blah
</xmlTag>

My XSL file

<?xml version="1.0"  encoding ="UTF-8" ?>
<xsl:stylesheet version="1.0 "
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/xmlTag">

        <head>
            <link rel="stylesheet" href="styles.css"/>
        </head>
        <html>
            <body id="id">
                 // some code
            </body>
        </html>

        <script src="./javaScript.js"></script> // link to my js file

    </xsl:template>
</xsl:stylesheet>

Js file

fetch('./Albums.xml').then(() => 2)

I need to change js file or approach (The connection between files)?
How can I get xml values from Js ?

Thanks guys really appreciate

6 thoughts on “How to get access XML file from Javascript (two ways and every thing bug )”

  1. This function below will get the ./Albums.xml file, parse it and return it as an XMLDocument. It uses the DOMParser API to turn a string of XML into an actual XML document which you can use in JavaScript.

    const getXML = async (file) => {
      const response = await fetch(file);
      const xmlString = await response.text();
      const parser = new DOMParser();
      const xml = parser.parseFromString(xmlString, 'text/xml');
      return xml;
    };
    
    getXML('./Albums.xml').then(xml => {
      console.log(xml);
    });
    

    Your XSLT file has an faulty order in the HTML part. See that the <head> is outside of the <html> tag here below?

    <head>
      <link rel="stylesheet" href="styles.css"/>
    </head>
    <html>
      <body id="id">
        <!-- Some code -->
      </body>
    </html>
    

    That should be inside of the ` tag, otherwise it won’t work.

    <html>
      <head>
        <link rel="stylesheet" href="styles.css"/>
      </head>
      <body id="id">
        <!-- Some code -->
      </body>
    </html>
    

    Some advice for in the future. Steer clear from W3Schools regarding old subjects like the one you presented. The code you’ve just shown us is ancient and should not be used in this day and age.

    Reply
  2. I’m not to sure, what you are looking for. I tried the Tutorial and it worked.

    // const xmlUrl = '/whatever.xml';
    const xmlUrl = URL.createObjectURL(new Blob([`<?xml version="1.0" encoding="UTF-8"?>
    <catalog>
      <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
      </cd>
      <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
        <company>CBS Records</company>
        <price>9.90</price>
        <year>1988</year>
      </cd>
    </catalog>
    `]));
    
    // const xlsUrl = '/whatever.xsl';
    const xslUrl = URL.createObjectURL(new Blob([`<?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
      <h2>My CD Collection</h2>
      <table border="1">
        <tr bgcolor="#9acd32">
          <th style="text-align:left">Title</th>
          <th style="text-align:left">Artist</th>
        </tr>
        <xsl:for-each select="catalog/cd">
        <tr>
          <td><xsl:value-of select="title"/></td>
          <td><xsl:value-of select="artist"/></td>
        </tr>
        </xsl:for-each>
      </table>
    </xsl:template>
    </xsl:stylesheet>
    `]));
    
    function http_request(method, url, content, callback) {
        const xhr = new XMLHttpRequest();
        xhr.open(method, url, true);
        xhr.addEventListener('readystatechange', function() {
            if (xhr.readyState !== 4 || xhr.status !== 200) {
                return;
            }
            if (!!callback && typeof callback === 'function') {
                callback(xhr);
            }
        });
        xhr.send(content);
    }
    
    http_request('GET', xmlUrl, void 0, function (xml) {
        const xmlObject = xml.responseXML;
        http_request('GET', xslUrl, void 0, function (xsl) {
            const xslObject = xsl.responseXML;
            const xsltProcessor = new XSLTProcessor();
            xsltProcessor.importStylesheet(xslObject);
            const resultDocument = xsltProcessor.transformToFragment(xmlObject, document);
            document.getElementById("example").appendChild(resultDocument);
        });
    });
    <div id="example"></div>
    Reply

Leave a Comment