Welcome !

Read, comment and forward on your own risk :-)

Saturday, November 21, 2009

Displaying XML code in HTML

In my previous post about playlist for WD TV I wanted to show some XML examples. From endless reading of developer blogs and sites I know that the best practice is to show the block of code in its own section, easy for copying, preferably indented and, as a bonus, with the syntax highlight. After compromising on the last one, the quickest solution I find for the problem is to use the <pre> tag with some extra style definitions.
First of all, the XML has to be converted to replace the bracket and other characters with HTML entities, their decimal or hexadecimal codes. There are several tools for this task, including text editors with Text2HTML converters or online tools such as http://htmlentities.net. If the indentation is important - make sure you’re source XML is indented before the conversion.
The next step is to define the HTML section that will contain your XML:
<pre style="background-color: #F5F5F5; border-left: 2px solid silver; padding: 5px; overflow:auto;">CONVERTED XML GOES HERE...</pre>


If you have several XML code sections, you can reuse the same technique or define the style for all <pre> tags by the stylesheet file that could be used for several pages or in the <head> section for this page only. I guess, it should be possible to add this to my Blogger definitions and use it automatically for all my posts – maybe I’ll check this in the future. Meanwhile, here is the second technique: style override at the <head> section that will be applied each time you’ll use <pre> tag.

<head>
<style type="text/css">
pre{ background-color: #F5F5F5; border-left: 2px solid silver; padding: 5px; overflow:auto; }
</style>
</head>

No comments: