How to Display an XML Document?
While XML's primary purpose is to structure and transport data, you will often need to view an XML file to inspect its contents. Modern web browsers are excellent tools for this, but it's crucial to understand what you are seeing and why.
Let's see how to view a raw XML file in a browser, why it doesn't look like a web page, and introduce the technologies that are used to transform XML into a human-readable and styled format.
Viewing a Raw XML File in a Browser
The easiest way to view an XML file is to simply open it in a modern web browser like Chrome, Firefox, or Edge. You can do this by:
- Dragging and dropping the
.xmlfile into an open browser window. - Using the
File > Open File...menu in your browser.
When you do this, the browser will not render it like an HTML page. Instead, it will act as an "XML viewer," typically providing a collapsible, color-coded tree view of the nodes.
For example this XML code:
<table xmlns="http://www.w3.org/TR/html4/">
<tr>
<td>Milan</td>
<td>Rome</td>
<td>Venice</td>
</tr>
</table>
will be viewed as:
Some browsers report errors if an invalid XML file is opened, others show an error message or highlight the wrong XML code.
This behavior of browsers is not standard.
Why is the style missing in the XML code?
Why XML Doesn't "Display" Like HTML
The fundamental difference between XML and HTML is their purpose.
- HTML is for displaying data. Its tags have a predefined meaning that tells the browser how to render content (e.g.,
<h1>means "a large heading"). - XML is for describing data. Its tags are custom-defined by you and have no inherent visual meaning.
When a browser sees an XML tag like <book>, it doesn't know if that should be a large heading, a paragraph, or an item in a list. Without instructions, all it can do is show you the raw structure of the data.
If you want to style an XML document, use XSLT. XSLT (Extensible Stylesheet Language Transformations) is the standard and most powerful technology for transforming XML into other formats, especially HTML. An XSLT stylesheet is a set of rules that tells a processor how to convert the XML tree into a different tree structure.
Conclusion
- XML documents can be viewed directly in a browser, which will typically display a color-coded, interactive tree of the raw data. This is useful for inspection and debugging.
- XML itself contains no display information. Unlike HTML, its tags are for describing data, not for formatting.
- To style and display an XML document for an end-user, you must provide a stylesheet, either with CSS (for simple styling) or XSLT (for a full transformation into HTML).