blue       earthtones
 
Chemical Formulas in Dynamic XHTML Pages

Discussion: Chemical formulas in dynamic xhtml pages, whether the data source be an XML file, JSON file, or a relational database, present an interesting formatting challenge for the web developer. Let's consider the case of XML:  when creating an XML file, it is possible to embed markup in a given element by enclosing it in CDATA (i.e., unparsed character data) markers, but in nearly all cases it is equally pointless to do so since the element content is treated, as specified by CDATA, as unparsed character data. Consequently it is rendered as simple text rather than as the developer might have intended.

For example, consider an XML element which contains embedded markup:

<ChemicalFormula><![CDATA[H<sub>2</sub>O]]></ChemicalFormula>

while the developer might wish this to be rendered on the web page as "H2O", in reality it will be escaped and rendered as "H<sub>2</sub>O" since it is by definition "unparsed".

Solution: A simpler, and for a host of reasons far preferable, approach is illustrated below. Using client-side JavaScript, it's very straightforward to parse a "flat" chemical formula from an XML element, JSON array, or database column and replace the id.innerHTML with a reformatted version of the formula which produces the intended rendering.

Click the mineral name below to see the canonical rendering. The JavaScript code to do this is here (transported via the XMLHttpRequest object). This JavaScript was originally developed as a live solution for a geology website's Mineral Database.

<MineralName>the <ChemicalFormula> element:the canonical rendering:

CancriniteNa6Ca(CO3)(AlSiO4)6ยท2H2O 

Horneblende(Ca,Na)2-3(Mg,Fe,Al)5Si8Al2O22(OH)2 

PyrrhotiteFe0.8-1.0S