XML DOM nodeName 属性

定義と用法

nodeName 属性は、そのタイプに応じてノードの名前を返します。

文法

documentObject.nodeName

インスタンス

例 1

以下のコードは "books.xml" を xmlDoc に読み込み、根ノードのノード名とノードタイプを表示します:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       myFunction(this);
   }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    document.getElementById("demo").innerHTML =
    "ノード名: " + xmlDoc.nodeName +"
    " (ノードタイプ: " + xmlDoc.nodeType + ")"
}

実際に試してみる

例 2

すべての要素の nodeName と nodeValue を表示する:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
    var x, y, i, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.documentElement;
    y = xmlDoc.documentElement.childNodes;
    for(i = 0; i < y.length; i++) {
        if (y[i].nodeType != 3) {
            txt += "ノード名: " + y[i].nodeName +
            " (値: " + y[i].childNodes[0].nodeValue + ")<br>"
        }
        for(z = 0; z < y[i].childNodes.length; z++) {
            if (y[i].childNodes[z].nodeType != 3) {
                txt += "ノード名: " + y[i].childNodes[z].nodeName +
                " (値: " + y[i].childNodes[z].childNodes[0].nodeValue + ")<br>"
            }
        }
    }
    document.getElementById("demo").innerHTML = 
    "ノード名: " + xmlDoc.nodeName +"
    " (値: " + xmlDoc.childNodes[0].nodeValue + ")<br>" +
    "Nodename: " + x.nodeName + 
    " (値: " + x.childNodes[0].nodeValue + ")<br>"
    txt;
}

実際に試してみる