尝试将XML转换为JsTree的JSON(Javascript/Jquery) [英] Trying to convert XML to JSON for JsTree (Javascript/Jquery)

查看:59
本文介绍了尝试将XML转换为JsTree的JSON(Javascript/Jquery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一些本地应用.我曾经学习过如何开发,但是还没有实践过7年.而且我很生锈.

I'm trying to create some local app. I used to learn how to dev, but havent practiced at all for 7 years. And i'm pretty rusty.

我有一个带有输入的HTML页面.此输入应为XML文件. 目的是使用JsTree构建该文件的树,然后单击"leaf"中的一个,在另一个div中显示说明.

I have an HTML page with an input. This input should be a XML file. The aim is to build a tree of that file using JsTree, and when i click on one of the "leaf", showing the description in another div.

好吧,我处理了"div"部分.但是我在读取文件时遇到了一些麻烦.

Well, i handled the "div" part. But i have some troubles with file reading.

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

This is what my XML file looks like (just a sample) :

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

And this is the JsTree i wanna have :

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

如果您对如何执行操作有任何想法,那就太好了. 我正在挣扎.如果我应该重新处理XML文件,也可以说:)

If you have any idea on how to do it, would be nice. I'm struggling. If i should rework the XML file, just say it too :)

这实际上是我所得到的

如果可以帮助您,这是我的代码,用于在上方的链接中获取图片.

Edit : If that can help, here is my code to get the image in the link right above.

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是我的输入. 树容器是应该加载树的div.

loadXmlButton is my input. tree-container is the div where the tree is supposed to load.

推荐答案

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

You can use this function to convert XML to 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一起使用:

And then, you can use it with 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) });

这篇关于尝试将XML转换为JsTree的JSON(Javascript/Jquery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆