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

时间:2012-02-07 10:50:48

标签: javascript xml

我已经在我的下一页中设置了一个变量,这个变量是我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时,我想要显示必杀技和led +描述,所以相应节点的全部内容。

编辑我已经尝试了代码并且似乎只得到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>")
    }
}
事先提前

1 个答案:

答案 0 :(得分:3)

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

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