Using xml-stylesheet to Link CSS and XSLT
The xml-stylesheet processing instruction allows
developers to associate external stylesheets—specifically CSS or
XSLT—with an XML document to control how raw data is displayed or
transformed. By inserting this directive into the XML prolog, user
agents like web browsers are instructed to either apply visual styling
directly to XML elements using CSS or transform the XML structure into
HTML or another format via XSLT prior to rendering.
Syntax and Placement
The xml-stylesheet directive is a processing instruction
that must be placed in the XML document’s prolog, appearing after the
XML declaration (<?xml version="1.0"?>) but before
the opening tag of the root element.
The basic syntax uses pseudo-attributes similar to standard HTML attributes:
<?xml-stylesheet attribute="value" attribute="value" ... ?>Associating CSS with XML
When linking a CSS stylesheet, the XML elements are styled directly
without altering the underlying document tree. The browser treats the
XML tags as generic block or inline elements, requiring explicit CSS
rules (such as display: block;) to format them legibly.
To link a CSS file, set the type attribute to
text/css and reference the stylesheet’s location in the
href attribute:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="styles.css"?>
<catalog>
<item>
<name>Product 1</name>
<price>$19.99</price>
</item>
</catalog>Associating XSLT with XML
When linking an XSLT (Extensible Stylesheet Language Transformations) file, the browser processes the transformation rules defined in the stylesheet to convert the XML source into a new document—typically HTML—before rendering it to the screen.
To link an XSLT stylesheet, specify the MIME type as
text/xsl or application/xslt+xml and point to
the .xsl or .xslt file in the
href attribute:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="transform.xsl"?>
<catalog>
<item>
<name>Product 1</name>
<price>$19.99</price>
</item>
</catalog>Common Pseudo-Attributes
The xml-stylesheet processing instruction supports
several pseudo-attributes to manage how the stylesheet is fetched and
applied:
href(Required): The URI pointing to the stylesheet file.type(Required): The MIME type of the target stylesheet (e.g.,text/cssortext/xsl).media(Optional): Specifies the intended display medium, such asscreen,print, orall.title(Optional): Assigns a title to the stylesheet, often used when grouping preferred or alternate stylesheets.alternate(Optional): Set toyesto declare an alternative stylesheet, orno(default) for the primary stylesheet.charset(Optional): Specifies the character encoding of the external stylesheet file.