Skip to main content

How to display XML code on an HTML page

There may be instances when you want to show sample XML code on a web page. I'm referring to the raw XML code with any and all markup intact. When the browser believes that the entire page is an XML page (because the page begins with an XML declaration), it will usually do the right thing and display the XML. If, however, you have the XML on an HTML page, the XML markup will be read by the browser instead of displayed.

For example, here is some sample XML data:

<?xml version="1.0" encoding="ISO-8859-1"?>

Aliya
Yasir
Note
Hello!

If you put these lines in an HTML page, they will not display correctly because they look like markup code. Without any modification, they will look like this:

<?xml version="1.0" encoding="ISO-8859-1"?>

Aliya
Yasir
Note
Hello!

The fix is pretty simple. Replace all instances of the open bracket and close bracket with their corresponding HTML character entities, e.g. < and >. After doing so, the HTML should look like the following:

<?xml version="1.0" encoding="ISO-8859-1"?> <text> <to>John</to> <from>Ed</from> <heading>Note</heading> <body>Hello!</body> </text>

When the above HTML is displayed in a browser, the character entities become brackets and the XML data will display correctly. If you do a view source on this web page and look at the first block of XML code above, you will see that it displays correctly because it is using character entities!

When you have a lot of code to display, you may want to use your favorite text editor to search and replace all instances of < and >.