Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...