?

Log in

No account? Create an account
Transform XML into a Javascript object - Argument

> Recent Entries
> Archive
> Friends
> Profile

Links
Mike Gonzalez (The only good blogger on the internet)
Bitdesigns ~ Bit Santos

November 3rd, 2007


Previous Entry Share
12:14 am - Transform XML into a Javascript object
After the Wordpress editor crashed all three of my browsers (Firefox, IE, Opera), I decided to say "screw it" and post here instead of the blog I made for the stuff that's boring to the public at large.

I’ve been looking for a Javascript way to navigate through an XML document like an object. That is, I wanted to take an XML document returned from an AJAX request (eg:
<book>
  <author>
     <name>Miguel</name>
  </author>
  <title>Hello</title>
</book>
), and go through it by saying something like “book.author.name”. Surprisingly, it was very difficult to find a solution–or more accurately, impossible. I had figured that this was something someone would have invented long ago, but I actually couldn't any implementations of this idea. I ended up writing my own function, and I’ve posted it below. (I realize that I could have saved effort by using JSON instead, but XML I don't think you'll always be able to get a JSON representation for a project)

I get the impression that this function is going to be slow–I put each node into an array (in case there are multiple nodes with the same name), and afterwards, flatten any arrays of length 1. However, I don't think it's slow enough to have any visible effect on small files (you have no business doing it with big files anyhow!). Any comments are welcome, as this code probably has shortcomings. For starters, it will flatten any array of length 1, even if it makes more sense to keep it as an array (eg: a grocery list consisting of one item should still be an array). Also, this code gets attributes as well, so be sure not to have any conflicting names. I'm sure there I made other unsafe assumptions, but for now, it works on Firefox, Opera, and IE.
    function createObj(xml) {
var obj = {};
if(xml.attributes) {
for(var j = 0; j < xml.attributes.length; j++) {
obj[xml.attributes[j].name] = xml.attributes[j].value;
}
}
for(var i = 0; i < xml.childNodes.length; i++) {
var x = xml.childNodes[i];
/* Note: IE and Opera do not define Node or its constants. You'll need to define them yourself
* for the benefit of said browsers.
*
* Meanwhile, the childNodes.length check is there because Firefox counts any whitespace as text nodes.
* This function, then, will only work on the assumption that "real" text nodes are the lone content
* of their parents.
*/
if ((x.nodeType == Node.TEXT_NODE && xml.childNodes.length == 1)) {
return x.nodeValue;
}
if (x.nodeType == Node.ELEMENT_NODE) {
// Assume a child node consisting of the empty string if there are no further children.
if (x.childNodes.length == 0) {
return "";
}
if (!obj[x.nodeName]) {
obj[x.nodeName] = $A();
}
obj[x.nodeName][obj[x.nodeName].length] = createObj(x);
}
}

for(var a in obj) {
if(obj[a] instanceof Array && obj[a].length == 1) {
obj[a] = obj[a][0];
}
}
return obj;
}

(3 comments | Leave a comment)

Comments:


From:(Anonymous)
Date:January 9th, 2011 11:54 am (UTC)

pmsqvjhm smlx

(Link)
phghswy mrh zdezi pornstar galleries (http://www.pornstars234.com/pornstar galleries.html)

bxfxy!

kpekr rjudgt tnx asian lesbians (http://www.asianporn234.com/asian lesbians.html)
From:(Anonymous)
Date:February 8th, 2011 12:24 am (UTC)

[url=http://www.dopimmo.com]immobilier location[/url]

(Link)
Les tarifs de l’ [url=http://www.dopimmo.com]immobilier achat[/url] ancien pourraient accuser une nouvelle chute d’au moins 10% sur les douze prochains mois, suivi de nouveaux replis de 5% en 2010 et de 3% en 2011.
Aprcs un premier repli de 3,1% en 2008, les prix de l’ [url=http://www.dopimmo.com]immobilier location[/url] ancien pourraient accuser une nouvelle chute d’au moins 10% sur l’an prochain. Et la reduction devrait se poursuivre les annיes suivantes si l’on se fie aux scיnario les plus pessimistes avancיs par la Fnaim.
D’aprcs une יtude publiיe ce matin, la Fיdיration nationale des agences [url=http://www.dopimmo.com]immobilier[/url] rappelle en effet que la chute s’est fortement accיlיrיe en fin d’annיe… Aprcs avoir enregistrי un recul de 2,9% au cours du 3cme trimestre, les prix des logements anciens se sont effondrיs de prcs de 6,5% au cours du seul 4cme trimestre de 2008.
La baisse des taux enclenchיe fin 2008 ne suffira donc pas r renverser la tendance et r relancer la demande r court terme. Plusieurs raisons r cela. Depuis quelques mois, les agences immobilieres constatent que les nיgociations sont de plus en plus tendues entre vendeurs et acheteurs. « Surtout, malgrי des taux qui repassent en dessous de la barre des 5%, il est r craindre que les banques ne desserrent pas facilement leurs conditions de crיdit dans les mois r venir. Pour l’heure, les exigences d’apport personnels restent toujours trcs strictes : autour de 10 r 20% en moyenne », observe Renי Pallincourt, prיsident de la Fיdיration nationale des agences immobilieres
Face r ce constat, la Fnaim prיfcre donc parier sur une stabilisation du marchי r horizon 2012. « Une nouvelle baisse d’au moins 10% est encore nיcessaire pour rיtablir la solvabilitי des mיnages et permettre de relancer le marchי [url=http://www.dopimmo.com]immobilier location[/url]» note Renי Pallincourt. Compte tenu de l’יvolution incertaine de la crise יconomique, la Fיdיration s’avance meme, pour la premicre fois, r יvoquer de nouvelles baisses de prix au cours des prochaines annיes. La Fnaim anticipe ainsi un repli de 5% en 2010 et de 3% en 2011.
From:(Anonymous)
Date:February 23rd, 2011 02:13 pm (UTC)

Знакомства FairLove

(Link)
Девушки и Парни для знакомств на FAIRLOVE.RU
выбор анкет для знакомства.
Для Секса, для Брака, для Интриг, для Развлечений, для Жизни.
Russian DATING on Fairlove.ru
Бесплатно: просмотр анкет, фотографий, регистрация, подбор партнёра, размещение анкет.
Знакомства,в Москве, в Санкт-Петербурге, в России и СНГ
Знакомство с девушками и парнями, мужчинами и женщинами, и не только...

> Go to Top
LiveJournal.com