[英]Can't retrieve nodes from XML doc in Javascript using getElementsByTagName
我正在嘗試制作一個本質上具有兩個滾動框的html頁面,一個可以在其中查看樹狀結構,類似於文檔中節點名稱的視圖(我將其設置為創建按鈕而不是純文本),然后當您單擊樹視圖中的節點名稱,它將在另一個框中顯示該節點的值和屬性名稱。 我正在使用w3schoools建議的標准加載方法加載文檔
function openSourceXML(){
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
;
xmlhttp.open("GET",
"file:///C:/Users/conada/Downloads/FOPwc/dictionary.dic", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
};
我可以使用...構造樹視圖部分沒有問題
function start() {
x = xmlDoc.documentElement;
document.getElementById("root").innerHTML = xmlDoc.documentElement.nodeName;
document.write("<br><b><font color=\"rgb(33,0,255)\" size=\"6\">"
+ x.nodeName + "</b></font>");
printChildren(x, 1);
function printChildren(node, depth) {
for ( var i = 0; i < node.childNodes.length; ++i) {
if (node.childNodes[i].nodeName != "#text") {
document.write("<br>");
if (depth == 1)
document.write("<b><font color=\"0000FF\" size=\"5\">");
if (depth == 2)
document.write("<font color=\"0088DD\" size=\"4\">");
if (depth == 3)
document.write("<font color=\"3318BB\" size=\"4\">");
if (depth == 4)
document.write("<font color=\"006688\" size=\"4\">");
if (depth == 5)
document.write("<font color=\"00DDFF\" size=\"4\">");
for ( var j = 0; j < depth; j++) {
document
.write("  ");
}
document.write("<button type=\"button\" onClick=\"writeSome(this.value)\" value=\"" + node.childNodes[i].nodeName + "\">" + node.childNodes[i].nodeName +"</button>");
if (depth == 1)
document.write("</b></font>");
if (depth == 2)
document.write("</font>");
if (depth == 3)
document.write("</font>");
if (depth == 4)
document.write("</font>");
};
printChildren(node.childNodes[i], depth + 1);
};
};
};
當您單擊按鈕時,它會調用一個函數,並向其傳遞所選節點的名稱。然后,該函數嘗試使用getElementsByTagName檢索所需的節點,無論這是如何停止的。 到目前為止,此功能僅顯示您應該獲取的節點的名稱,然后在嘗試獲取節點后輸出名稱(在邏輯上應匹配)。 單擊按鈕所調用的功能是...
function writeSome(value){
currNode=value;
//output passed string to ensure there is no problem there
document.getElementById("rightPane").innerHTML = currNode + "<br>";
//try to grab the node you want
x = xmlDoc.getElementsByTagName(currNode);
//display the name of the node to ensure the right node was found (should match name passed in)
document.getElementById("rightPane").innerHTML += x.nodeName + "<br>";
};
這些功能全部在我的html外部的一個文件中。 為什么getElementsByTagName似乎什么也不做? 如果沒有這種方式,我如何訪問給定名稱的特定節點? 因為我已經用盡了解決此問題的想法,所以任何幫助都會非常有用。
另外,請注意,我已經驗證了一些訪問XML文件的功能可以正常工作,例如使用xmlDoc.documentElement檢索根節點,然后使用.childNodes遍歷文件,但這對我來說用處不大,只想抓住我正在快速且干凈地尋找的特定節點。
我認為您的問題可能是您缺少數組索引。 getElementsByTagName
返回一個元素數組,您需要指定要使用的元素。
x=xmlDoc.getElementsByTagName(currNode)[0];
您還應該注意,“ getElementsByTagName”將返回具有該標簽的所有節點的數組,而不僅僅是一個節點(除非您只有一個帶有該標簽的節點)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.