client browser using JavaScript. Normally I wouldn’t entertain the
thought but with the recent push of AJAX and various cross-browser
script libraries I thought I’d take another look. NB. This doesn’t
consider JSON, I’ll post on that option later.
XmlDocument
The
core requirement to most XML processing (ignoring SAX style processing)
is the document. AJAX has helped here and it seems that the majority of
browsers implement some form of Dom but they do suffer from
inconsistencies.
HttpRequest
Probably the most
reliable object is HttpRequest, which is a necessity for AJAX. There
is a cross-browser issue but it’s fairly simple to solve…
if(window.XMLHttpRequest && !(window.ActiveXObject))…
httpRequest = new XMLHttpRequest();
…
if(window.ActiveXObject)
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
after
that the objects seem to use the same API. There does seem to be some
drawbacks with this approach, you need a web site (or service) to get
the XML from and the lack of XPath support.
XmlDocument revisited
"But
I don’t want to fetch my XML from a site, I created it on the client",
I hear you cry. Well most browsers support the following…
if (document.implementation && document.implementation.createDocument)…
xmlDoc = document.implementation.createDocument("", "", null);
…
if (window.ActiveXObject)
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
similar
in nature to the previous cross-browser test. These have good DOM
support and you can create/append elements as you’d expect. The load
method seemed a bit flaky. Now this maybe my code so I’ll hold off
saying it doesn’t work…but it didn’t seem to! But creating the DOM
manually seemed fine so it is still useful, especially for sending data
back. However, the biggest issue seems to be XPath
XPath
XPath is a very useful API for searching XML but its support in
browsers is very patchy. Mozilla based browsers offer a good implementation…
var paragraphCount = document.evaluate( ‘count(//p)’, xmlDocument, null, XPathResult.ANY_TYPE, null );
and it includes NodeIterator for a selectNodes style enumerating.
Microsoft has the more usual (I’m an MS developer) SelectNodes, again
very easy to abstract out the difference in API. However…Safari. The
Konqueror based browser simply doesn’t like XPath. So what to do? I
considered writing my own query engine but I don’t really want to waste
my time re-inventing the wheel. So I had a look for a script library,
but it seems like XPath libraries and are still in their infancy. Of
the ones out there XML for SCRIPT
looked promising but still not 100%. At this point I realised that for
my specific needs I could get away with a bit of DOM walking so I left
it there.
Conclusion
My conclusion is that XML support in the browser is ok if you base your
work around HttpRequest. But if you want to do XPath then look for an
alternative.