簡體   English   中英

使用javascript進行xml dom解析

[英]xml dom parsing using javascript

我對javascript完全陌生。 我需要javascript中的代碼,該代碼可讀取外部xml文件並將每個值記錄到控制台中。 以下代碼是否會錯過將文件加載到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>

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>

與評論相反,您實際上可以在沒有ajax的情況下執行此操作。 實現此目的的方法是給我們一個iframe ,您可以根據需要將其設置為hidden。

考慮與您一樣的html文檔,但iframe除外:

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

您的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