How To Display Xml In Html

XML (eXtensible Markup Language) is a markup language created as a standard for data representation and exchange on the web. While XML is similar to HTML in its structure, it serves a different purpose, and cannot be displayed directly in a web browser like HTML can. However, there are times when you might want to display XML data within an HTML page, and this guide will show you how to do that.

Method 1: Using JavaScript and DOM Parsing

This method involves using JavaScript to parse the XML data and convert it into HTML elements. Here are the steps to do this:

  1. Load the XML data as a string. This can be done by fetching the XML file using the fetch function or embedding the XML data in the HTML page as a string.
  2. Create a DOM parser to parse the XML string into XML nodes.
  3. Iterate through the XML nodes and convert them to HTML elements.
  4. Append the HTML elements to the HTML page.

Example

Suppose we have the following XML data that represents a list of books:

        
<books>
  <book>
    <title>The Catcher in the Rye</title>
    <author>J.D. Salinger</author>
  </book>
  <book>
    <title>To Kill a Mockingbird</title>
    <author>Harper Lee</author>
  </book>
</books>
        
    

To display this XML data in an HTML page, we can use the following JavaScript code:

document.addEventListener(‘DOMContentLoaded’, function() {
const xmlString = `


The Catcher in the Rye
J.D. Salinger


To Kill a Mockingbird
Harper Lee


`;

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, ‘text/xml’);
const books = xmlDoc.getElementsByTagName(‘book’);

const bookList = document.createElement(‘ul’);

for (let i = 0; i < books.length; i++) {
const title = books[i].getElementsByTagName(‘title’)[0].textContent;
const author = books[i].getElementsByTagName(‘author’)[0].textContent;
const listItem = document.createElement(‘li’);
listItem.textContent = `${title} by ${author}`;
bookList.appendChild(listItem);
}

document.body.appendChild(bookList);
});

Method 2: Using XSLT (Extensible Stylesheet Language Transformations)

XSLT is a language designed for transforming XML documents into other formats, such as HTML or other XML documents. With XSLT, you can create a stylesheet that defines how the XML data should be displayed in HTML, and then apply this stylesheet to the XML data.

Example

To display the XML data from the previous example using XSLT, we can create the following XSLT stylesheet file (bookList.xsl):

        
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <ul>
          <xsl:for-each select="books/book">
            <li>
              <xsl:value-of select="title"/> by <xsl:value-of select="author"/>
            </li>
          </xsl:for-each>
        </ul>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
        
    

To apply the XSLT stylesheet to the XML data, we can use the following JavaScript code:

async function loadXMLDoc(xmlFile, xslFile) {
const xmlResponse = await fetch(xmlFile);
const xmlData = await xmlResponse.text();
const xmlParser = new DOMParser();
const xmlDoc = xmlParser.parseFromString(xmlData, ‘text/xml’);

const xslResponse = await fetch(xslFile);
const xslData = await xslResponse.text();
const xslParser = new DOMParser();
const xslDoc = xslParser.parseFromString(xslData, ‘text/xml’);

const xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xslDoc);

const resultDocument = xsltProcessor.transformToFragment(xmlDoc, document);
document.body.appendChild(resultDocument);
}

document.addEventListener(‘DOMContentLoaded’, function() {
loadXMLDoc(‘bookList.xml’, ‘bookList.xsl’);
});

Conclusion

In this guide, we covered two methods to display XML data in an HTML page: using JavaScript and DOM parsing, and using XSLT. Both methods have their advantages and limitations, and the choice depends on your specific requirements and familiarity with the technologies involved.