gpt4 book ai didi

javascript - 我如何使用javascript获取xml中某个标题的内容?

转载 作者:行者123 更新时间:2023-11-29 20:11:56 25 4
gpt4 key购买 nike

我在下一页的 url 中设置了一个变量,这个变量是我的 xml 中一篇文章的标题。我试图获取本文中的其余内容,但不幸地失败了……xml 的布局是。

    <title>
<artist>
Nirvana
</artist>
<description>
Nirvana in concert
</description>
<date>
18/05/1987
</date>
</title>
<title>
<artist>
led zeppelin
</artist>
<description>
led in concert
</description>
<date>
18/05/1987
</date>
</title>

当我搜索 18/05/1987 时,我想显示 nirvana 和 led + description,所以相应节点的全部内容。

编辑 我已经尝试了代码,但似乎只得到了 1 个答案......我很新,所以我不明白为什么在检查时我没有得到更多答案

    xmlDoc=loadXMLDoc("data.xml");
var hash = getUrlVars();
var date = hash['date'];
var nodeList = xmlDoc.getElementsByTagName("article");

for (var i = 0; i < nodeList.length; i++) {
var titleNode = nodeList[i];
if(titleNode.getElementsByTagName("urltext")[i].nodeValue = date){
document.write("<div style='width:450px;'>")
document.write("<p>"+titleNode.getElementsByTagName("title")[i].childNodes[0].nodeValue+"</p>");
document.write("<p>"+titleNode.getElementsByTagName("description")[i].childNodes[0].nodeValue+"</p>");
document.write("<p>"+titleNode.getElementsByTagName("urltext")[i].childNodes[0].nodeValue+"</p>");
document.write("</div>")
}
}

提前准备好

最佳答案

这是我用来创建我可以使用的 XML DOM 文档的一个小 JavaScript 函数...

function GetXMLDoc(xml) {
var xmlDoc;
if (window.DOMParser) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(xml, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xml);
}

return xmlDoc;
}

然后您可以像这样使用它来获取标题,例如...

var xmlDoc = GetXMLDoc(XML_String_Input);
var title = xmlDoc.getElementsByTagName("title")[0].nodeValue;

编辑:当您似乎想要对 XML 执行搜索时,您可以执行类似这样的操作...

var nodeList = xmlDoc.getElementsByTagName("title");
var resultNodes = [];

for (var i = 0; i < nodeList.length; i++) {
var titleNode = nodeList[i];
if(titleNode.getElementsByTagName("artist")[0].nodeValue == "Nirvana"){
//match found for artist "Nirvana"
resultNodes.push(titleNode);
}
}

//here you will now have a list (`resultNodes`) of "title" nodes that matched the search (i.e. artist == "Nirvana")
//there is enough sample code above for you to be able to process each of the seach results and gets the values for the various other properties like "data" for example

See here for more information on XML DOM function and properties

关于javascript - 我如何使用javascript获取xml中某个标题的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9174921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com