Adding JavaScript to XML

Adding JavaScript to XML is a little bit tricky. I first used to transform the target XML document into an HTML one by using XSLT. It worked fine, but I was frustrated by the idea of adding another PI to the XML set. So I asked myself: how can a browser recognize a script element as such? In fact, if you try to add this kind of tag to an XML document, the script and everything is contained within the tag is parsed as CDATA so that nothing happens except viewing the contents of your script displayed on the page.

The answer is simple: a browser recognizes a script because it is part of an HTML DTD. More precisely, in the case of XML the DTD in question is an XHTML DTD. But this is not enough: a browser recognizes a script element not only because is part of the XHTML DTD, but also because it lives within the XHTML global namespace, which is also an XML standard namespace. The global XHTML namespace is as follows:

http://www.w3.org/1999/xhtml

This namespace must be added to the root element of your XML document. By doing so, browsers will treat your scripts as normal XHTML elements, because they live inside the XHTML namespace. Example:

<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://www.w3.org/1999/xhtml">
     
 <para>Test</para>
 
 
 
   
 
    <script type="text/javascript">
    
    <![CDATA[
    
    
    
    
    
    
       alert(document.getElementsByTagName('para')[0].firstChild.nodeValue); // alerts 'Test'
       
       
       ]]>
       
       
    
    </script>
    
   
 
 
 
</root>

As you can see, the root element has the default XHTML namespace attached to it. In this way, the script element is parsed as an XHTML element and not as a generic XML element.

Leave a Reply

Note: Only a member of this blog may post a comment.