繁体   English   中英

如何在javascript中编写代码以读取xml文件

[英]How can I write a code in javascript to read xml files

我只是想知道我该如何使用JavaScript和HTML编写代码以使XML文件正常工作。 我目前正在使用此代码,但无法正常工作

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<p>
<h1 id="to">To:
<h1 id="from">From:
<h1 id="message">Message:
<p>
</div>

<script>
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
} 
else{ 
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","FileName.xml", false); 
xmlhttp.send(); 
xmlDoc=xmlhttp.responseXML;

document.getElementById("to").innerHTML = xmlDoc.getElementsByTagName("to").childNodes[0].nodeValue;
document.getElementById("from").innerHTML=xmlDoc.getElementsByTagName("from").childNodes[0].nodeValue;
document.getElementById("message").innerHTML=xmlDoc.getElementsByTagName("message").childNodes[0].nodeValue;
</script>
</body>
</html>

我正在使用此XML代码

<?xml version="1.0" encoding="UTF-8"?>
<e-mail>
<to>John</to>
<from>Larry</from>
<message>Hello how are you!</message>
</e-mail>

您缺少关闭</h1>标记,而且<h1>不是<p>元素的有效子元素; 使用XMLHttpRequest() .onload事件通过.responseText执行任务; 在调用getElementsByTagName()之后添加索引[0]以引用HTMLCollection特定元素

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div>
    <h1 id="to">To:</h1>
    <h1 id="from">From:</h1>
    <h1 id="message">Message:</h1>
  </div>
  <script>
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    } else {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", "FileName.xml", false);
    xmlhttp.onload = function() {
      xmlDoc = xmlhttp.responseXML;
      document.getElementById("to").innerHTML = xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
      document.getElementById("from").innerHTML = xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
      document.getElementById("message").innerHTML = xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;
    }
    xmlhttp.send();
  </script>
</body>
</html>

plnkr https://plnkr.co/edit/jLsO3SgV8dMG3sRBZbds?p=preview

暂无
暂无

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

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