To format XML, you can use Extensible Stylesheet Language Transformations (XSLT). XSLT helps convert XML into HTML using stylesheets. Then, you can apply regular CSS to style the resulting HTML content.
In the case of the XML example you mentioned, here is a sample stylesheet:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="note">
<p> <xsl:value-of select="body"/> </p>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
This stylesheet would generate a properly structured HTML document displaying the body of the note
element as per your provided example.
You can execute XSLT within a Greasemonkey script using XSLTProcessor()
like this:
// ==UserScript==
// @name _XML renderer / styler
// @description stylesheet for xml results
// @include http://YOUR_SERVER.COM/YOUR_PATH/*.xml
// @include http://www.w3schools.com/xml/note.xml
// @grant none
// ==/UserScript==
//-- Note that multiline strings are not universally supported yet.
var xsl_str = `<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
<title>Customized note format</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body { padding: 0 2em; }
.noteCtr {
border: 1px solid gray;
border-radius: 1ex;
padding: 0;
background: #FAFAFA;
}
.messPeople { font-size: 1em; margin: 1ex 1em; }
.messHeading { background: lightcyan; margin: 0 1.6ex; }
.messHeading::after { content: ":"; }
.noteCtr > p {
background: white;
padding: 1em;
margin: 0 1em 1.5ex 1em;
}
</style>
</head>
<body>
<xsl:for-each select="note">
<div class="noteCtr">
<h3 class="messPeople">
<xsl:value-of select="from"/>
-->
<xsl:value-of select="to"/>
</h3>
<h3 class="messHeading"> <xsl:value-of select="heading"/> </h3>
<p> <xsl:value-of select="body"/> </p>
</div>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
`;
var processor = new XSLTProcessor();
var dataXSL = new DOMParser().parseFromString(xsl_str, "text/xml");
processor.importStylesheet(dataXSL);
var newDoc = processor.transformToDocument(document);
//-- Replace the current document with the newly processed one...
window.content = newDoc;
document.replaceChild(
document.importNode(newDoc.documentElement, true),
document.documentElement
);
For more complex tasks, consider fetching the stylesheet using a @resource
directive instead. Follow this guide.
Install the script and view the sample XML page to see it in action.
You will witness the transformation from the original XML structure to the customized HTML layout...
Original:
Formatted Output: