2011-10-14 3 views
4

Quelle est la meilleure fonction javascript/plugin/bibliothèque pour convertir une chaîne XML en JSON.Outil (javascript) pour convertir une chaîne XML en JSON

J'ai trouvé cet outil: http://www.thomasfrank.se/xml_to_json.html, mais il n'aime pas les chaînes commençant par 0. à savoir: 005321 se convertir à 2769 (pas cool :()

Ma question, quelle est la meilleure fonction javascript/plugin/bibliothèque pour convertir un XML en JSON

EDIT: Quelqu'un a essayé un qui fonctionne bien?

+0

pourquoi ne pas essayer d'écrire à l'auteur à ce sujet? – stivlo

+0

@stivlo - Il y a une grande note en haut de la page qui dit que l'auteur veut que les gens utilisent autre chose "en raison de nombreux problèmes signalés". –

+0

Ce script ne génère même pas de JSON valide, tel qu'il est. – Pointy

Répondre

16

Cette fonction a assez bien fonctionné pour moi:

xmlToJson = function(xml) { 
    var obj = {}; 
    if (xml.nodeType == 1) {     
     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) { 
     obj = xml.nodeValue; 
    }    
    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; 
} 

Mise en œuvre:

var jsonText = JSON.stringify(xmlToJson(xmlDoc)); // xmlDoc = xml dom document 
+0

Grande solution !! Merci –

+0

Vous êtes les bienvenus. –

+0

Une amélioration pratique: si vous changez 'typeof (obj [nom_noeud] .length) ==" undefined "' en 'typeof (obj [nom_noeud] .push) ==" non défini ", il arrête de souffler sur les espaces et les éléments de texte entre les balises. – jpatokal

1

Si vous êtes prêt à utiliser jQuery, il y a:

http://www.fyneworks.com/jquery/xml-to-json/

$.get("http://jfcoder.com/test.xml.php", function(xml){ 
    var json = $.xml2json(xml); 
    $('pre').html(JSON.stringify(json)); // To show result in the browser 
}); 

utilisant:

<nums> 
<num>00597</num> 
<num>0059</num> 
<num>5978</num> 
<num>5.978</num> 
</nums> 

Sorties:

{"num":["00597","0059","5978","5.978"]} 

http://jfcoder.com/test.php

+0

Cette bibliothèque perd les balises incorporées dans le texte: '

Bonjour gras et italique

' devient '{" p ":" Helloand "}'. – jpatokal

Questions connexes