如何从XML&中选择一个随机子元素显示子子元素;用JS?

时间:2018-04-26 16:53:12

标签: javascript xml random

我想从XML文件中获取数据,以显示在通过单击按钮获得的html页面中。单击该按钮时,我希望选择一个随机子项,并显示子子数据。我制作了一个如下所示的XML文件:

<?xml version="1.0" encoding="UTF-8"?>
 <kdramas>
  <kdrama>
    <title lang="en">A Gentleman's Dignity</title>
    <genre>Comedy, Romance, Drama</genre>
    <year>2012</year>
    <episodes>20</episodes>
    <about>This drama will tell the story of four men in their forties as they go through love, breakup, success and failure. </about>
</kdrama>
<kdrama>
    <title lang="en">Boys Over Flowers</title>
    <genre>Comedy, Romance, Drama, School</genre>
    <year>2009</year>
    <episodes>25</episodes>
    <about>about text</about>
</kdrama>
<kdrama>
    <title lang="en">Goblin</title>
    <genre>Comedy, Romance, Melodrama, Supernatural</genre>
    <year>2016</year>
    <episodes>16</episodes>
    <about>about text</about>
</kdrama>

我可以在单击按钮时显示XML数据,但它显示所有数据(标题除外)。我环顾四周,看看是否有可能选择一个随机的孩子,然后显示其子子元素,但到目前为止,我没有找到任何运气。我必须显示XML数据的JS代码是:

function getDrama(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("content").innerHTML =
    this.responseText;
    document.getElementById("content").style.display = "block";
  }
};
xhttp.open("GET", "https://raw.githubusercontent.com/npellow/npellow.github.io/master/kdramaList.xml", true);
xhttp.send();
}

关于如何做到这一点的任何想法?或者甚至只是将我指向一个我可以阅读如何自己做的地方会很棒?

2 个答案:

答案 0 :(得分:1)

使用JQuery构造$(_ your_text _)。find('_ elenent_name_')查找数据:

function getDrama(_callback){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    //document.getElementById("content").innerHTML = this.responseText;
    //document.getElementById("content").style.display = "block";
    _callback(this.responseText);
  }
};
xhttp.open("GET", "https://raw.githubusercontent.com/npellow/npellow.github.io/master/kdramaList.xml", true);
xhttp.send();
}

function get_random_title(){
   getDrama(function(_text){
   	  var titles_length = $(_text).find('kdrama').length;
   	  var random_number = 1 + Math.floor(Math.random() * titles_length);
   	  var random_title = $(_text).find('kdrama').eq(random_number).find('title').text();
	  $('#content').html( random_title );
   });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


  <div id="content"></div>


  <input type="button" value="Get Random Title" onClick="get_random_title();">

答案 1 :(得分:0)

我建议将XML转换为JSON以便于处理,您可以使用此处的功能https://davidwalsh.name/convert-xml-json

你得到了kdramas数组,然后选择一个随机元素。只需要格式化JSON进行打印。

&#13;
&#13;
function xmlToJson( xml ) {
  // Create the return object
  var obj = {};
 
  if ( xml.nodeType == 1 ) { // element
    // do attributes
    if ( xml.attributes.length > 0 ) {
    obj["@attributes"] = {};
      for ( var j = 0; j < xml.attributes.length; j++ ) {
        var attribute = xml.attributes.item( j );
        obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
      }
    }
  } else if ( xml.nodeType == 3 ) { // text
    obj = xml.nodeValue;
  }
 
  // do children
  if ( xml.hasChildNodes() ) {
    for( var i = 0; i < xml.childNodes.length; i++ ) {
      var item = xml.childNodes.item(i);
      var nodeName = item.nodeName;
      if ( typeof(obj[nodeName] ) == "undefined" ) {
        obj[nodeName] = xmlToJson( item );
      } else {
        if ( typeof( obj[nodeName].push ) == "undefined" ) {
          var old = obj[nodeName];
          obj[nodeName] = [];
          obj[nodeName].push( old );
        }
        obj[nodeName].push( xmlToJson( item ) );
      }
    }
  }
  return obj;
}

function getDramaList(callback){
 		var xhttp = new XMLHttpRequest();
  	xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        var xmlDOM = new DOMParser().parseFromString(this.responseText, 'text/xml');
        var jsonXml = xmlToJson(xmlDOM);
        callback(jsonXml.kdramas.kdrama);
      }
  	};
  	xhttp.open("GET", "https://raw.githubusercontent.com/npellow/npellow.github.io/master/kdramaList.xml", true);
 		xhttp.send();
}
getDramaList(function(dramaList){
	var randomIndex = Math.floor(Math.random(0,dramaList.length));
	var randomKdrama = dramaList[randomIndex];
	document.getElementById("content").innerHTML = JSON.stringify(randomKdrama, null, "&emsp;").replace(/\n/g,"<br>");
	document.getElementById("content").style.display = "block";
});
&#13;
<div id="content">
</div>
&#13;
&#13;
&#13;