假设我有以下XML
<building>
<phonenumber></phonenumber>
<room>
<phonenumber></phonenumber>
</room>
</building>
使用building.getElementsByTagName('phonenumber')
,我还获得<phonenumber>
下的<room>
节点。
如何只选择<phonenumber>
下的直接building
节点?
答案 0 :(得分: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>
答案 1 :(得分: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;
}