查找XML节点的直接子节点

时间:2010-12-13 02:52:56

标签: javascript html xml

假设我有以下XML

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

使用building.getElementsByTagName('phonenumber'),我还获得<phonenumber>下的<room>节点。

如何只选择<phonenumber>下的直接building节点?

2 个答案:

答案 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;
}