javascriptxmljstree

Populating jstree from xml string


I am trying to populate a jstree container with data from a string describing an xml document. Here's my code, with a simplified xml document:

var xmlText = "<root>A<node>B</node></root>";
var xml = (new DOMParser()).parseFromString(xmlText,'text/xml');    
$('#jstree').jstree({"core": {data: xml.documentElement}});

(also on codepen: http://codepen.io/szymtor/pen/XKqApq/).

The result is a well-structured tree, but without node labels (see image below). How should I provide the node labels? Or am I doing it wrong?

resulting jstree


Solution

  • Support for XML seems limited. The documentation of version 3 only speaks of HTML or JSON input for jstree(), even though in earlier versions there was a xml_data plug-in that could be activated for XML support.

    I would suggest you would just work around this, by converting your XML to a JSON with this function:

    function xmlToJson(xmlNode) {
        return {
            text: xmlNode.firstChild && xmlNode.firstChild.nodeType === 3 ? 
                      xmlNode.firstChild.textContent : '',
            children: [...xmlNode.children].map(childNode => xmlToJson(childNode))
        };
    }
    

    See this example:

    function xmlToJson(xmlNode) {
        return {
            text: xmlNode.firstChild && xmlNode.firstChild.nodeType === 3 ? 
                      xmlNode.firstChild.textContent : '',
            children: [...xmlNode.children].map(childNode => xmlToJson(childNode))
        };
    }
    
    var xmlText = "<root>A<node>B<node>C</node></node></root>";
    
    var xml = (new DOMParser()).parseFromString(xmlText,'text/xml');
    
    $('#jstree').jstree({
        core: {
          data: xmlToJson(xml.documentElement)
        }
    });
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
    <div id="jstree">
    </div>