Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Using the XSLT function document()

I found an XSLT solution recently using the built-in function document() to include an additional XML document into the current XML document.

Using the file lunch.xml with drink.xml I can show what is available for today's lunch menu.

file: lunch.xml
<food>
  <item name="banana"/>
  <item name="apple"/>
  <item name="custard"/>
  <item name="crisps"/>
</food>  


file: drink.xml
<drinks>
  <drink name="water"/>
  <drink name="orange"/>
  <drink name="lemonade"/>
  <drink name="cream soda"/>
  <drink name="tea"/>
  <drink name="coffee"/>
  <drink name="blackcurrant juice"/>
  <drink name="ginger ale with lime"/>
</drinks>


file: lunch.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="food">
<html>
  <head><title>Food menu</title></head>
  <body>
  <h1>To eat</h1>
  <ul>
  <xsl:apply-templates select="item" />
  </ul>
  <h1>To drink</h1>
  <xsl:value-of select="document('drink.xml')/drinks/drink[2]/@name"/>
  </body>
</html>
         
</xsl:template>

<xsl:template match="item">
  <li><xsl:value-of select="@name"/></li>
</xsl:template>

</xsl:stylesheet>



output:
<html><body>
<h1>To eat</h1>
<ul>
<li>banana</li>
<li>apple</li>
<li>custard</li>
<li>crisps</li>
</ul>
<h1>To drink</h1>orange</body></html>

Extract the filename from a URL

This ECMAScript extracts the filename from a URL. eg. the filename 'index4.svg' would be extracted from the document.URL with the value 'http://rorbuilder.info/r/whiteboardqueue/index4.svg'.
var regexp = /(\w|[-.])+$/
str = document.URL
a = regexp.exec(str)
alert(a[0])

Reference: Regular Expressions: Methods - Doc JavaScript [webreference.com]

Reading an XML file using JavaScript

Reads an xml file using JavaScript from a web page. Files used: loadxml.js (main script), readxml.js (client script), and readxml.html. The code for loadxml.js was copied from the article JavaScript and XML [devarticles.com]

file: loadxml.js
  XML.load = function(url) {
    var xmldoc = XML.newDocument();
    xmldoc.async = false;  
    xmldoc.load(url);
    return xmldoc;  
  };


XML.newDocument = function(rootTagName, namespaceURL) {
    if (!rootTagName) rootTagName = "";
    if (!namespaceURL) namespaceURL = "";

    if (document.implementation && document.implementation.createDocument) {
        // This is the W3C standard way to do it
        return document.implementation.createDocument(namespaceURL, 
                       rootTagName, null);
    }
    else { // This is the IE way to do it
        // Create an empty document as an ActiveX object
        // If there is no root element, this is all we have to do
        var doc = new ActiveXObject("MSXML2.DOMDocument");

        // If there is a root tag, initialize the document
        if (rootTagName) {
            // Look for a namespace prefix
            var prefix = "";
            var tagname = rootTagName;
            var p = rootTagName.indexOf(':');
            if (p != -1) {
                prefix = rootTagName.substring(0, p);
                tagname = rootTagName.substring(p+1);
            }

            // If we have a namespace, we must have a namespace prefix
            // If we don't have a namespace, we discard any prefix
            if (namespaceURL) {
                if (!prefix) prefix = "a0"; // What Firefox uses
            }
            else prefix = "";

            // Create the root element (with optional namespace) as a
            // string of text
            var text = "<" + (prefix?(prefix+":"):"") + tagname +
                (namespaceURL
                 ?(" xmlns:" + prefix + '="' + namespaceURL +'"')
                 :"") +
                "/>";
            // And parse that text into the empty document
            doc.loadXML(text);
        }
        return doc;
    }
}; 


file: readxml.js
function readXmlFile() {
  url = 'http://rorbuilder.info/pl/test123';

  doc = XML.load(url);
  alert(doc.documentElement.firstChild.nextSibling.firstChild.nodeValue);
}


file: readxml.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Read an XML file</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <script type="text/javascript" src="js/loadxml.js"/>
    <script type="text/javascript" src="js/readxml.js"/>
  </head>

  <body>
    <h1>ReadXML</h1>
    <p>
       If all goes well you should see an alert box display the message 'testing 123'
   </p>
    <p>Press the 'go' button to read the xml file '<a href="test123">test123</a>' 
       from the web server. 
       <input type="button" onclick="readXmlFile()" value="go"/>
    </p>

    
  </body>
</html>


Note: To avoid the cross-site security error message 'permission denied', store all the files on the same web server.

To test the above code try out the demo to read the xml file [rorbuilder.info].

instapaper bookmarklet

Assuming you are registered with the new bookmarking service 'instapaper', then you would use the following code which would normally be placed as a link within your web browser's toolbar.

javascript:var d=document,w=window,e=w.getSelection,k=d.getSelection,x=d.selection,
s=(e?e():(k)?k():(x?x.createRange().text:0)),f='http://www.instapaper.com/b',
l=d.location,e=encodeURIComponent,p='?v=3&u='+e(l.href) +'&t='+e(d.title) +'&s='+e(s),
u=f+p;try{if(!/^(.*\.)?instapaper([^.]*)?$/.test(l.host))throw(0);
iptstbt();}catch(z){a =function(){if(!w.open(u,'t','toolbar=0,resizable=0,status=1,
width=250,height=150'))l.href=u;};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);
else a();}void(0)


I'm interested in using similar JavaScript if I ever write my own personal bookmarking service.
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS