首页 > 解决方案 > 具有自定义 xml 或 json 结构的 JsTree

问题描述

我有一个如下所示的 XML 结构:

<RootFeature>
<Name>MainFeature</Name>
<Subfeatures>
    <Feature>
        <Name>Feature1</Name>
        <Subfeatures>
            <Feature>
                <Name>Feature1_1</Name>
        </Feature>
            <Feature>
                <Name>Feature1_2</Name>
        </Feature>
            <Feature>
                <Name>Feature1_3</Name>
        </Feature>
        </Subfeatures>
    </Feature>
    <Feature>
        <Name>Feature2</Name>
    </Feature>
    <Feature>
        <Name>Feature3</Name>
        </Feature>
    <Feature>
        <Name>Feature4</Name>
        </Feature>
    <Feature>
        <Name>Feature5</Name>
    </Feature>
    <Feature>
        <Name>Feature6</Name>
    </Feature>
    <Feature>
        <Name>Feature7</Name>
    </Feature>
</Subfeatures>

我想在上面使用 Jstree,并创建一棵树。我尝试将 Jstree 直接应用到它(XML)上,结果与本主题中解释的结果相同:

从 xml 字符串填充 jstree

将其转换为 Json 后(使用以下库:https://goessner.net/download/prj/jsonxml/),我有这个:

 "RootFeature":{
"Name":"Feature1",
"Subfeatures":{"Feature":[
{
  "Name":"Feature1",
  "Subfeatures":{"Feature":[
    {"Name":"Feature1_1"},
    {"Name":"Feature1_2"},
    {"Name":"Feature1_3"}
    ]}
},
{"Name":"Feature2"},
{"Name":"Feature3"},
{"Name":"Feature4"}, 
{"Name":"Feature5"},
{"Name":"Feature6"},
{"Name":"Feature7"}
]}

我搜索了如何在我的结构上应用 Jstree,知道我必须遵循某种格式,其中<Name>标签必须替换为<text><Subfeatures>by<children>并摆脱<Feature>标签。

我在论坛上找到了这个主题:JsTree with custom json data but could not apply the solution..老实说,我完全不理解。

我什至尝试使用 Json 数据递归地重新创建树,但我无法创建一个数组“Children”,其中包含多个具有相同名称“text”的元素,每个元素都有一个值(最后就像一个 Json 文件)。它是:

"Children":
"text1":"Feature1",
"text2":"Feature2",
"text3":"Feature3",

或者

"Children":
"0":"Feature1",
"1":"Feature2",
"2":"Feature3",

如果有人知道我如何使用我的结构处理 Jstree,或者有任何想法,不客气。

谢谢

标签: javascriptjsonxmljstreejstree-search

解决方案


jsTree 需要特定格式的数据来创建树。您的结构需要解析为类似于此处描述的 JSON 结构。将 XML 转换为 JSON 后,您可以在其上使用如下解析器。

function getFeature(s, t) {
    t.text = s["Name"] ? s["Name"] : "";
    if (s.hasOwnProperty("Subfeatures")) {
        t.children = []; 
        s.Subfeatures.Feature.forEach(function (f, i) {
            t.children.push({})
            getFeature(f, t.children[i]);
        });
    }
}

function ParseData() {
    //Convert XML to JSON prior to this.

    var oSourceJSON = {
        "RootFeature": {
            "Name": "Feature1",
         ...
         ...
         ...

    };

    var result = [];
    if (oSourceJSON.hasOwnProperty("RootFeature")) {
        result.push({});
        getFeature(oSourceJSON.RootFeature, result[0]);
    }
    return result;
}

$(document).ready(function () {
    $('#jstree_demo_div').jstree({
        core: {
            //Note: If you use an external service use a callback method here
            data: ParseData()
        }
    });
});

推荐阅读