MIME Test - XPath Test

Back to the MIME Type Tests.

Thank you to James Graham who sent in the following information about MIME types when using XPath.

When served as text/html, the following section of code indicates a single heading:

function xpath()
{
    var numHeadings;
    var resultNode = document.getElementById("result");
    var headings = document.evaluate("//h1", document, null, 
                   XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

    if (headings.snapshotLength)
        numHeadings = headings.snapshotLength;
    else
        numHeadings = 0;

    var result = document.createTextNode(numHeadings);
    resultNode.appendChild(result);

    return false;
}

When served as application/xhtml+xml this won't work because the tag name (e.g. h1) is no longer a single name, it's two part; a URI representing the namespace and a tag name. The URI is represented by a prefix which is mapped onto the URI by the xmlns attribute. Therefore, to make the same document work when served as application/xhtml+xml, two changes are needed: the tag names must be replaced by a prefix:name pair (e.g. html:h1) and the call to document.evaluate must be supplied with a namespace resolving function that converts the prefix to a URI. See Interface XPathEvaulator for more details. That leads us to the following.

function NSResolver(prefix)
{
    if (prefix=="html")
        return "http://www.w3.org/1999/xhtml";

    return null;
}

function xpath()
{
    var resultNode = document.getElementById('result');
    var headings = document.evaluate('//html:h1', document, NSResolver, 
                   XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

    if (headings.snapshotLength)
        var numHeadings = headings.snapshotLength;
    else
        numHeadings = 0;

    var result = document.createTextNode(numHeadings);
    resultNode.appendChild(result);
    return false;
}

This document won't work as text/html, so at least the problem is symmetric :)

Using the first code example served as text/html, the xpath function calulates that this document has h1 heading(s).