2010-12-13 120 views
4

假设的直接孩子,我有以下XML找到一个XML节点

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

使用building.getElementsByTagName('phonenumber'),我也得到<room><phonenumber>节点。

我该如何选择building下的立即<phonenumber>节点?

回答

3

嗯,我被骗和使用jQuery的。那么,不是每个人?

<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

你知道一种方法来计算直接孩子的属性吗?用alert($(this).attributes.length)替换each()函数的内容会显示错误,指出.attributes未定义。 – Dave 2010-12-13 03:42:09

+1

试试这个:alert($(this)[0] .attributes.length) – mattmc3 2010-12-13 04:43:57

+0

它的工作原理。非常感谢你。 – Dave 2010-12-13 04:57:57

0

这不能单独使用getElementsByTagName来完成,因为它总是搜索元素下面的整个子树。

你可以尝试使用XPATH,或只是遍历的<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; 
}