2010-12-13 17 views
4

Supposons que j'ai le code XML suivantTrouver les enfants immédiats d'un noeud XML

<building> 
    <phonenumber></phonenumber> 
    <room> 
     <phonenumber></phonenumber> 
    </room> 
</building> 

En utilisant building.getElementsByTagName('phonenumber'), je reçois aussi le nœud <phonenumber> sous <room>.

Comment puis-je choisir uniquement le noeud <phonenumber> immédiat sous building?

Répondre

3

Eh bien, je triché et utilisé jQuery. Alors encore, tout le monde ???

<html> 
<body> 

<script type="text/javascript" src="https://www.google.com/jsapi"></script> 
<script language="javascript" type="text/javascript"> 
google.load("jquery", "1.4.4"); 
</script> 

<script language="javascript" type="text/javascript"> 
// taken from http://plugins.jquery.com/project/createXMLDocument so that I could 
// play with the xml in a stringy way 
jQuery.createXMLDocument = function(string) { 
    var browserName = navigator.appName; 
    var doc; 
    if (browserName == 'Microsoft Internet Explorer') { 
     doc = new ActiveXObject('Microsoft.XMLDOM'); 
     doc.async = 'false' 
     doc.loadXML(string); 
    } 
    else { 
     doc = (new DOMParser()).parseFromString(string, 'text/xml'); 
    } 
    return doc; 
} 

// here's the relevant code to your problem 
var txtXml = "<building><phonenumber>1234567890</phonenumber><room><phonenumber>NO!</phonenumber></room></building>"; 
var doc = $.createXMLDocument(txtXml); 
$(doc).find('building').children('phonenumber').each(function() { 
    var phn = $(this).text(); 
    alert(phn); 
}); 
</script> 

</body> 
</html> 
+0

Connaissez-vous un moyen de compter les attributs de l'enfant immédiat? Le remplacement du contenu de la fonction each() par alert ($ (this) .attributes.length) affiche une erreur indiquant que .attributes est indéfini. – Dave

+1

Essayez ceci: alert ($ (this) [0] .attributes.length) – mattmc3

+0

Cela fonctionne. Merci beaucoup. – Dave

0

Cela ne peut pas être fait avec getElementsByTagName seul, car il cherche toujours la sous-arborescence entière sous l'élément.

Vous pouvez essayer d'utiliser XPath ou boucle juste par les enfants immédiats de <building>:

function getPhoneNumber() { 
    var building = document.getElementsByTagName("building")[0]; 
    for (var i = 0; i < building.childNodes.length; i++) { 
     if (building.childNodes[i].tagName == "PHONENUMBER") { 
      return building.childNodes[i]; 
     } 
    } 
    return undefined; 
}