【问题标题】:Trying to convert XML to JSON for JsTree (Javascript/Jquery)尝试将 XML 转换为 JsTree 的 JSON (Javascript/Jquery)
【发布时间】:2018-10-02 08:51:02
【问题描述】:

我正在尝试创建一些本地应用程序。我曾经学习如何开发,但已经 7 年没有实践了。而且我很生疏。

我有一个带有输入的 HTML 页面。此输入应该是一个 XML 文件。 目的是使用 JsTree 构建该文件的树,当我单击其中一个“叶子”时,在另一个 div 中显示描述。

好吧,我处理了“div”部分。但是我在文件读取方面遇到了一些麻烦。

这是我的 XML 文件的样子(只是一个示例):

<offres>
    <formation>
        <domaine-formation>
            <groupName>domaine-formation</groupName>
            <groupDesc>Cet élément contient des listes de codes décrivant le dormaine de la formation, en utilisant les nomenclatures NSF (Nomenclatures des Spécialités de Formation), ROME (Répertoire Opérationnel des Métiers et des Emplois) et/ou le FORMACODE (thésaurus de l'offre de formation du Centre Inffo). Règle de gestion : le premier code FORMACODE doit être considéré comme le FORMACODE principal.</groupDesc>
            <occMin>1</occMin>
            <occMax>1</occMax>
            <code-FORMACODE>
                <dataName>code-FORMACODE</dataName>
                <dataType>Alphanumérique</dataType>
                <dataPresence>Conditionnel</dataPresence>
                <minLength>5</minLength>
                <maxLength>5</maxLength>
                <dataDesc2>Cet élément contient un code du FORMACODE. Il est obligatoire de préciser grâce à l'attribut 'ref' la version du FORMACODE utilisée (par exemple 'V10' pour la version 10 du FORMACODE).</dataDesc2>
                <txcompOI>99.7</txcompOI>
            </code-FORMACODE>
            <code-NSF>
                <dataName>code-NSF</dataName>
                <dataType>Alphanumérique</dataType>
                <dataPresence>Facultatif</dataPresence>
                <minLength>3</minLength>
                <maxLength>3</maxLength>
                <dataDesc2>Cet élément contient un code de la NSF (3 postes).</dataDesc2>
                <txcompOI>75.4</txcompOI>
            </code-NSF>
            <code-RNCP>
                <dataName>code-RNCP</dataName>
                <dataType>Alphanumérique</dataType>
                <dataPresence>Facultatif</dataPresence>
                <minLength>1</minLength>
                <maxLength>6</maxLength>
                <dataDesc2>Cet élément contient un code d'une certification dans le Répertoire National des Certifications Professionnelles.</dataDesc2>
                <txcompOI>34.6</txcompOI>
            </code-RNCP>
            <extras></extras> 
        </domaine-formation>
        <intitule-formation>
            <dataName>intitule-formation</dataName>
            <dataType>Alphanumérique</dataType>
            <dataPresence>Obligatoire</dataPresence>
            <minLength>1</minLength>
            <maxLength>255</maxLength>
            <dataDesc1>Intitulé qui sert à caractériser et singulariser une action de formation. Il en indique le titre.</dataDesc1>
            <dataDesc2>Cet élément décrit l'intitulé de la formation. Si la formation a comme résultat l'obtention d'un diplôme, le contenu de cet élément devrait utiliser une dénomination conforme aux tables de l'Éducation Nationale. Si la formation a comme résultat un titre ou une certification, le contenu devrait utiliser une dénomination conforme au contenu du Répertoire National des Certifications Professionnelles (RNCP).</dataDesc2>
            <txcompOI>100</txcompOI>
        </intitule-formation>
        <objectif-formation>
            <dataName>objectif-formation</dataName>
            <dataType>Alphanumérique</dataType>
            <dataPresence>Obligatoire</dataPresence>
            <minLength>1</minLength>
            <maxLength>3000</maxLength>
            <dataDesc1>Il peut s'agir d'une session de certification, de professionnalisation, de préparation à la qualification, de remise à niveau, de (re)mobilisation, de perfectionnement ou de création d'entreprise. Ces catégories sont de type administratif et sont décrites ci-dessous.</dataDesc1>
            <dataDesc2>Cet élément décrit l'objectif de la formation. Il décrit la ou les compétences à acquérir, à améliorer ou à entretenir.</dataDesc2>
            <txcompOI>89.9</txcompOI>
        </objectif-formation>
    </formation>
</offres>

这就是我想要的 JsTree:

offres
 -- formation
 -- -- domaine-formation
 -- -- -- code-FORMACODE
 -- -- -- code-NSF
 -- -- -- code-RNCP
 -- -- intitule-formation
 -- -- objectif-formation

如果您对如何操作有任何想法,那就太好了。 我正在挣扎。如果我应该重做 XML 文件,也请说出来 :)

编辑:This is actually what i get

编辑:如果有帮助,这是我在上面的链接中获取图像的代码。

var loadXmlButton = document.getElementById('loadXmlButton');
loadXmlButton.addEventListener('change', handleFileSelection, false);

function handleFileSelection() {
    var file = loadXmlButton.files[0],
        reader = new FileReader();

    waitForTextReadComplete(reader);
    reader.readAsText(file);

    fileName = file.name;
    fileName = fileName.substr(0, fileName.lastIndexOf('.'));
    // On remplace le champs de sélection du fichier par le nom du fichier chargé
    $("#dataFileName").text('Norme '+ fileName.toUpperCase());
}

function waitForTextReadComplete(reader) {
    reader.onloadend = function(event) {
        var text = event.target.result;

        parseTextAsXml(text);
    }
}

function parseTextAsXml(text) {
    var xml = (new DOMParser()).parseFromString(text, 'text/xml')

    var parser = new DOMParser(),
        xmlDom = parser.parseFromString(text, "text/xml");

        $(function () {
            // var sHTML = drawTreeFromXml(xmlDom);
            var sHTML = xmlToJson(xml.documentElement)

            $(document).ready(function(){
                $('#tree-container').jstree({
                    'core' : {
                        'data' : sHTML,
                        'themes' : {
                            'responsive' : true
                        }
                    },
                    "search": {
                        "case_insensitive": true,
                        "show_only_matches" : true
                    },
                    plugins: ["search"]
                }).bind("select_node.jstree", function (e, data) {
                    var href = data.node.a_attr.href;
                    var parentId = data.node.a_attr.parent_id;
                    if(href == '#')
                    return '';

                    //window.open(href);
                    $('html,body').animate({scrollTop: ($(href).offset().top-65)},'slow');

                });

                $('#tree-container').slimScroll({
                    height: '480px',
                    start: 'top'
                });

            $('#search').keyup(function(){
                $('#tree-container').jstree('search', $(this).val());
            });            
        });
    });
}

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

loadXmlButton 是我的输入。 tree-container 是应该加载树的 div。

【问题讨论】:

    标签: javascript jquery jstree


    【解决方案1】:

    您可以使用此函数将 XML 转换为 JSON

    // Changes XML to JSON
    function xmlToJson(xml) {
        // Create the return object
        var obj = {};
    
        if (xml.nodeType == 1) { // element
        // do attributes
        if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
        } else if (xml.nodeType == 3) { // text
            obj = xml.nodeValue;
        }
    
        // do children
        if (xml.hasChildNodes()) {
            for(var i = 0; i < xml.childNodes.length; i++) {
                var item = xml.childNodes.item(i);
                var nodeName = item.nodeName;
                if (typeof(obj[nodeName]) == "undefined") {
                    obj[nodeName] = xmlToJson(item);
                } else {
                    if (typeof(obj[nodeName].push) == "undefined") {
                        var old = obj[nodeName];
                        obj[nodeName] = [];
                        obj[nodeName].push(old);
                    }
                    obj[nodeName].push(xmlToJson(item));
                }
            }
        }
        return obj;
    };
    

    然后,您可以将它与 JSTree 一起使用:

    var xml = `<offres>
        <formation>
            <domaine-formation>
                <groupName>domaine-formation</groupName>
                <groupDesc>Cet élément contient des listes de codes décrivant le dormaine de la formation, en utilisant les nomenclatures NSF (Nomenclatures des Spécialités de Formation), ROME (Répertoire Opérationnel des Métiers et des Emplois) et/ou le FORMACODE (thésaurus de l'offre de formation du Centre Inffo). Règle de gestion : le premier code FORMACODE doit être considéré comme le FORMACODE principal.</groupDesc>
                <occMin>1</occMin>
                <occMax>1</occMax>
                <code-FORMACODE>
                    <dataName>code-FORMACODE</dataName>
                    <dataType>Alphanumérique</dataType>
                    <dataPresence>Conditionnel</dataPresence>
                    <minLength>5</minLength>
                    <maxLength>5</maxLength>
                    <dataDesc2>Cet élément contient un code du FORMACODE. Il est obligatoire de préciser grâce à l'attribut 'ref' la version du FORMACODE utilisée (par exemple 'V10' pour la version 10 du FORMACODE).</dataDesc2>
                    <txcompOI>99.7</txcompOI>
                </code-FORMACODE>
            </domaine-formation>
        </formation>
    </offres>`,
    xmlDoc = $.parseXML( xml );
    
    $('#using_json').jstree({ 'core' : xmlToJson(xmlDoc) });
    

    【讨论】:

    • 我试过你的代码,但我什么也没得到。即使单独使用它。我试图用 'core' 更改 'core' : xmlToJson(xmlDoc) }) :{ 'data' : xmlToJson(xmlDoc) } })。我在 jstree 中得到一个没有名字(也没有子)的文件夹。
    猜你喜欢
    • 1970-01-01
    • 2015-08-15
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2013-11-25
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多