Home & blog  /  2011  /  Nov  /  view post  /

Additions to XML tree; jQuery XML parsing

posted: 24 Nov '11 08:45 tags: XML, tree, traversal, node, parsing

You may have seen my XMLTree plugin, posted a few weeks ago.

If you'll excuse the trumpet-blowing I do find this plugin among my most useful; I'm working on a number of projects right now that involve XML in the browser, and the ability to visualise it in a traversable tree is quiet satisfying.

New features (all documented on the script page) include:

- callback on resultant HTML - you can now specify a callback function which will be invoked after the tree has been generated. It is automatically passed a DOM reference to the tree ul so you can act on it.

- attributes - can now be ignored, hidden or shown. Hiding them is useful if you plan to traverse or interrogate the tree based on their existence or value, without wanting to show them to the user.

Bug fixes

This was an interesting one. With XMLTree you can either point it at an XML file for it to load, or manually pass it a well-formed string of XML.

In the latter case, it exploits a well-known (yet somewhat abused) perk of jQuery - that you can pass it a DOM or XML string and it will turn it into a nodeset.

But because this is intended for DOM creation, not XML creation, it assumes you're parsing an HTML document, not XML. The problem? If your XML contains any tags that share their names with any self-closing HTML tags, jQuery renders your XML invalid.

Consider the following example:

1var xml = "<root><link>http://mitya.co.uk</link></root>";

2console.log($(xml).html());

The output of that will be:

<link />http://mitya.co.uk

...which is obviously not what you'd wanted.

As a fix for this XMLTree now renames (secretly) all of the node names - but restores their original names on output.

Ideally, of course, I wouldn't be lazy and rely on jQuery to parse XML - there are native ways (albeit different ones for different browsers). But for now this fix works just fine.

Head over here to download, get usage info or view a demo.

post new comment

Comments (0)