0

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>
4

1 回答 1

0

这是因为您缺少 return 语句并引用声明的 objects 属性而不是使用's bodythis中的关键字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);
     }  
}
于 2013-01-30T21:49:13.177 回答