Entry
How can I link in a style sheet dynamically into an xml document?
Oct 2nd, 2001 03:59
Martin Honnen,
With xml documents, style sheets are linked to a document with a
processing instruction of the form
<?xml-stylesheet type="text/css" href="whatever.css"?>
Such a processing instruction belongs into the so called document prolog
after the xml declaration before the document type node.
Using DOM core methods you can create a processing instruction and
insert it into the document before the document.doctype node to
dynamically link in a style sheet.
The following example code has been tested with Mozilla 0.9.4 and works,
however Mozilla currently solves the problem of restyling the document
by reloading it which doesn't seem like an efficient and mature
solution.
Here is the example xml document:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE document>
<document xmlns:html="http://www.w3.org/1999/xhtml"
xmlns:xlink="http://www.w3.org/1999/xlink"
>
<html:script>
function linkStyleSheet (url) {
var pi = document.createProcessingInstruction('xml-stylesheet',
'type="text/css" href="' + url + '"');
document.insertBefore(pi, document.doctype);
}
</html:script>
<html:input type="button" value="load gods.css"
onclick="linkStyleSheet('gods.css')"
/>
<html:br/>
<gods>
<god>
<name>Kibo</name>
<home xlink:type="simple"
xlink:href="http://www.kibo.com">http://www.kibo.com</home>
</god>
</gods>
</document>
And here is an example CSS style sheet for gods.css:
gods { display: table; width: 100%; background-color: gold; }
god { display: table-row; }
name { display: table-cell; }
home { display: table-cell; }