javascript读取XML文件返回undefined

时间:2013-01-30 21:33:17

标签: javascript html xml

JavaScript的: 我在FireFox上使用以下代码来读取XML文件内容: HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>javascript ?? xml??</title>  
<script type="text/javascript" src="readXML.js"></script> 
</head>  
<body>  
</body>  
</html>  

javascript:

readMyXML={
    init: function(){
        readMyXML.javaScriptReadXML();
    },

    javaScriptReadXML: function(){
        var xmlDoc =document.implementation.createDocument("", "", null);        
        //xmlDoc = new ActiveXObject("MSXML2.DOMDocument.3.0");
        xmlDoc.async= false;                                         
        xmlDoc.load('PAS1.xml');              /* load XML file */
        //xmlDoc.load('myxml.xml');
        var objNodeList = xmlDoc.getElementsByTagName("Slide");
        var Node=objNodeList.item(0);
        var mytext=Node.getElementsByTagName("Context");

         alert("length="+mytext.item(0).Language);
     }  
}

window.addEventListener('load', readMyXML.init,false);

但无论我是否尝试获取XML的任何内容,它都会在警报中显示未定义。 如何解决这个问题。

XML是这样的:

<?xml version="1.0" encoding="utf-8"?>
<Survey SurveyID="PAS1" Description="PAS first part">
<Slide SlideID="S-N1">
<Question>
<Context Language="English">We would like you to fill out a questionnaire </Context>

</Question>
<Input Optional="true">
<Nothing ChoiceID="1" />
</Input>
<Next />
</Slide>

1 个答案:

答案 0 :(得分:0)

因为您缺少return语句并引用声明的对象属性而不是使用this正文中的init关键字,所以重写它如下:

var readMyXML = {
    init: function(){
          this.javaScriptReadXML();
    },

    javaScriptReadXML: function(){
         var xmlDoc =document.implementation.createDocument("", "", null);        

         // xmlDoc = new ActiveXObject("MSXML2.DOMDocument.3.0");
         xmlDoc.async= false;                                         
         xmlDoc.load('PAS1.xml');              /* load XML file */

         // xmlDoc.load('myxml.xml');
         var objNodeList = xmlDoc.getElementsByTagName("Slide");
         var Node=objNodeList.item(0);
         var mytext=Node.getElementsByTagName("Context");
         alert("length="+mytext.item(0).Language);
     }  
}