尝试使用JavaScript“设计”XML

时间:2017-05-16 07:33:38

标签: javascript html xml

基本上,我正在读出一个XML文件,我想确保你能清楚地阅读这些内容。按照目前的方式,我试着读出来,你会得到一长串的内容。我宁愿这样做:

TITLE:VAL

TITLE:VAL2

等。我尝试使用HTML换行标记,但这不起作用。有什么建议?这是现在的输出:https://gyazo.com/f98de4fc8941874aea27ad03750f6955?token=981b91ccbeae94c64a15b76e654708b9

<!DOCTYPE html>
<html>
<body>

<div id="XMLDisplay">
    <p id="container"></p>
</div>

<script>
var paragraph = document.getElementById("container");
var xmlhttp, xmlDoc;
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "Opdracht1XML.xml", false);
        xmlhttp.send();
        xmlDoc = xmlhttp.responseXML;
        x = xmlDoc.getElementsByTagName("CD")[0].childNodes;
        z = xmlDoc.getElementsByTagName("CD")
        for (k = 0; k < x.length; k++) {          
                y = xmlDoc.getElementsByTagName("CD")[k].firstChild;
            for (i = 0; i < x.length; i++) //looping xml childnodes
            {            
                if (y.nodeType == 1) {
                    var elements = y.nodeName;
                    var values = y.firstChild.nodeValue;
                    paragraph.append(elements + ": " + values);
                }
                y = y.nextSibling;

            }
            document.write("<br/>");
        }
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

我自己找到了解决方案,谢谢你自己努力寻找解决方案!

(溶液:

<script>
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this);
    }
  };
  xmlhttp.open("GET", "Opdracht1XML.xml", true);
  xmlhttp.send();

function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var table="<tr><th>Title</th><th>Artist</th><th>Country</th><th>Company</th><th>Price</th><th>Year</th></tr>";
  var x = xmlDoc.getElementsByTagName("CD");
  for (i = 0; i <x.length; i++) { 
    table += "<tr><td>" +
    x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("COUNTRY")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("COMPANY")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue +
    "</td></tr>";
  }
  document.getElementById("table").innerHTML = table;
}
</script>