简体   繁体   English

使用javascript进行xml dom解析

[英]xml dom parsing using javascript

i'm completely new to javascript. 我对javascript完全陌生。 I need a code in javascript that reads an external xml file and logs each value into the console. 我需要javascript中的代码,该代码可读取外部xml文件并将每个值记录到控制台中。 Does the following code miss something like loading the file into the html page? 以下代码是否会错过将文件加载到html页面之类的东西?

<html>
<xml id="obj" src="books.xml"></xml>
<script>
    console.log(obj);
    var rootnode=document.documentElement;
    for(var i=0;i<rootnode.childNode.childNodes.length;++i)
        for(var j=0;j<rootnode.childNode.childNodes.length;++j)
            {
                console.log(rootnode.childNodes[i].childNodes[j].nodeValue);
            }
</script>
</html>

The books.xml file looks like this books.xml文件如下所示

<books>
<book id="b1">
    <name>Java</name>
    <author>Gosling</author>
    <price>600</price>
</book>
<book id="b2">
    <name>Javascript</name>
    <author>Brandon</author>
    <price>400</price>
</book>
</books>

You actually can do this without ajax, contrary to comments. 与评论相反,您实际上可以在没有ajax的情况下执行此操作。 The way to do it is to us an iframe , which you can set to hidden if you would like. 实现此目的的方法是给我们一个iframe ,您可以根据需要将其设置为hidden。

Consider an html document like yours, except with the iframe: 考虑与您一样的html文档,但iframe除外:

<html>
  <head><title>whatever</title></head>
  <body>
    <iframe id='data' src='books.xml'></iframe>
  </body>
</html>

Your javascript function can then be something like this: 您的javascript函数可以是这样的:

function getData(){
  var dataFrame = document.getElementById('data');
  // older versions of IE needed this guard
  var xml = dataFrame.contentDocument || dataFrame.contentWindow.document; 
  var books = xml.getElementsByTagName('book');
  // books is iterable, and you can further extract nodes from it just like HTML tags
  for (var i=0;i<books.length; i++) {
    console.log(books[i]);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM