javascript 使用javascript读取xml文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12085181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:17:32  来源:igfitidea点击:

Reading xml file using javascript

javascriptxml

提问by my name is xyz

I am using the below code to read one xml file which is located locally. But its not displaying the object of xmldoc. My code is

我正在使用以下代码读取一个位于本地的 xml 文件。但它没有显示 xmldoc 的对象。我的代码是

function loadXMLDoc(XMLname)
{
  var xmlDoc;
  if (window.XMLHttpRequest)
    {
    xmlDoc=new window.XMLHttpRequest();
    xmlDoc.open("GET",XMLname,false);
     xmlDoc.send("");
     return xmlDoc.responseXML;
   }

   else if (ActiveXObject("Microsoft.XMLDOM"))
   {
   xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async=false;
   xmlDoc.load(XMLname);
   return xmlDoc;
   }
   alert("Error loading document!");
   return null;
   }



   function f1()
   {
   var xmlDoc=loadXMLDoc(“test.xml”)
   var M = xmlDoc.getElementsByTagName(“article”);
   alert(M);
     }

Its not displaying the alert if i call the function f1.Thanks in advance

如果我调用函数 f1,它不会显示警报。提前谢谢

回答by V I J E S H

Better use Jquery function. Its working fine for me.

最好使用 Jquery 函数。它对我来说工作正常。

<script src="jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$.ajax({
    type: "GET",
    url: "read2.xml",
    dataType: "xml",
    success: function(xml) {
        $(xml).find('site').each(function(){

            var id = $(this).attr('id');
            var title = $(this).find('title').text();
            var url = $(this).find('url').text();
            $(this).find('desc').each(function()
            {
                var brief = $(this).find('brief').text();
                var long = $(this).find('long').text();
                alert("my "+brief );
                alert("my "+long );

            });
        });
    }
});
});

And the XML file format will be

而 XML 文件格式将是

my title1 url1

我的标题 1 url1

brf 1 long 1

brf 1 长 1

brf 2 long 2

brf 2 长 2