This is documentation for Mathematica 5, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)

Documentation / Mathematica / Add-ons & Links / XML Capabilities / Transforming XML /

Visualizing the XML Tree

Many XML tools display an XML document as a collapsible tree, where the nodes correspond to the elements of the document. This example shows how to produce a similar visualization using cell grouping in a Mathematica notebook.

We will do this by recursively traversing the SymbolicXML expression and for each XMLElement object, creating a CellGroupData expression that contains cells for each of that XMLElement object's attributes and children. Each nested CellGroupData expression will be indented from the previous one. We start with the function to process an XMLElement object.


Notice that we use the integer m for indentation. When we map XMLNote onto the XMLElement object's children, we pass a larger value for m, increasing the indentation for the child elements.

A CellGroupData expression contains a list of cells. In the above definition, we have only created a cell for the XMLElement x. However, we have then mapped XMLNote onto the attribute list. Since this returns a list, we need to use Apply[ Sequence] to the result in order to merge that list into the CellGroupData expression's list of cells. We then do the same thing to the children of the XMLElement.

However, we have not yet defined XMLNote to work on attributes. The attributes of an XMLElement object are stored in SymbolicXML as rules. In most cases, the rule contains two strings: the key and the value. However, when namespaces are involved, the first element of the rule may be a list containing two strings: the namespace and the key. We will need to make two definitions to handle the attributes.



We will need one more definition in order to process simple SymbolicXML expressions. The text nodes in an XML document are stored simply as String objects in SymbolicXML. Thus, we need a definition which handles String objects.


With these definitions in place, we can construct a simple notebook to visualize a basic XML document.





Since the default value of the option "IncludeEmbeddedObjects" is None, we did not alter comments, processing instructions, or anything else that would be stored in an XMLObject. Adding definitions for these is not difficult and would be a good exercise in processing SymbolicXML.