开发者

Finding immediate children of an XML node

Suppose I have the following XML

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

Using building.getElementsByTagName('phonenumber'), I also get the <phonenumber> node under <room>.

How can I choose only 开发者_如何学运维the immediate <phonenumber> node under building?


Well, I cheated and used jQuery. Then again, doesn't everyone???

<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>


This can't be done with getElementsByTagName alone, since it always searches the entire subtree beneath the element.

You could try using XPATH, or just loop through the immediate children of <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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜