2016-02-13 72 views
0

我想找到一個特殊的標籤,它等於PLAYER_NAME,然後使用一個標籤的價值(注)XML文件的.The結構是:查找XML文件中的標籤

<Result> 
    <Name>Player1</Name> 
    <job>0<job>     
    <Age>10</Age>     
</Result> 
<Notepad> 
    <Name>Player1</Name> 
    <Notes>example notes....<Notes> 
</Notepad> 

我使用下面的代碼,但它不返回任何「x.getElementsByTagName("PlayerName").childNodes[i].nodeValue」,當我檢查與警報。

<script> 
 
function myFunction(xml,player_name) { 
 
    var x, i, xmlDoc, notes; 
 
    xmlDoc = xml.responseXML; 
 
    x = xmlDoc.getElementsByTagName("Notepad") 
 
    
 
for(i=0;i<x.length;i++){ 
 
    if (x.getElementsByTagName("Name").childNodes[i].nodeValue == player_name) { 
 
     notes = x.getElementsByTagName("Notes").childNodes[i].nodeValue; 
 
\t 
 
\t document.getElementById("something").innerHTML = notes;} 
 
    }  \t 
 
} 
 
</script>

回答

0

通常情況下,上面的代碼與給定的XML內容將拋出一個錯誤:

Uncaught TypeError: x.getElementsByTagName is not a function

我測試。這是因爲Element.getElementsByTagName()方法返回現場的HTMLCollection元素。要處理這種集合中的某個節點,您需要直接指定節點位置。

function myFunction(xml, player_name) { 
     var x, i, xmlDoc, notes; 
     xmlDoc = xml.responseXML; 
     x = xmlDoc.getElementsByTagName("Notepad"); 

     for (i = 0; i < x.length; i++) { 
      if (x[i].getElementsByTagName("Name")[0].childNodes[i].nodeValue == player_name) { 
       notes = x[i].getElementsByTagName("Notes")[0].childNodes[i].nodeValue; 

       document.getElementById("something").innerHTML = notes; 
      } 
     } 
} 

這工作,給我打電話example notes....myFunction(xhttp.responseXML, 'Player1');

+0

感謝名單的時候,你救了我:)日 – Adi

+0

歡迎您! – RomanPerekhrest

1

對於你的情況XPath是更好的。我寫此功能對於你的目的:

/** 
* This function assumes xml document 
* and player name as a arguments and 
* returns notes for this player if 
* this player exists false otherwise. 
* 
* @author Georgi Naumov 
* [email protected] for contacts and 
* suggestions. 
*/ 
function getPlayerNotes(xmlDoc, playerName) { 
    var xpathQuery = [ 
     '//Notepad[Name[text()=\'', 
     playerName, 
     '\']]/Notes' 
    ].join(''), recordsCount; 

    recordsCount = xmlDoc.evaluate('count(' + xpathQuery + ')', xmlDoc, null, XPathResult.NUMBER_TYPE, null); 

    if (recordsCount.numberValue === 0) { 
     return false; 
    } 

    return (xmlDoc.evaluate(xpathQuery, xmlDoc, null, XPathResult.STRING_TYPE, null)).stringValue; 
} 

在這裏你可以看到演示如何使用功能:

http://gonaumov.github.io/javaScriptXpath/

而且輸入的XML必須有效。檢查示例輸入字符串。