gpt4 book ai didi

javascript - 在 XML 文件中查找标签

转载 作者:行者123 更新时间:2023-12-03 07:41:37 26 4
gpt4 key购买 nike

我想找到一个等于player_name的特殊标签,然后使用下一个标签的值(注释)。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;

document.getElementById("something").innerHTML = notes;}
}
}
</script>

最佳答案

对于你的情况,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
* gonaumov@gmail.com 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 也必须有效。检查示例输入字符串。

关于javascript - 在 XML 文件中查找标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386554/

26 4 0