[英]How can I write a code in javascript to read xml files
I just wanted to know that how can i write code in using JavaScript and HTML in order to make XML file work. 我只是想知道我该如何使用JavaScript和HTML编写代码以使XML文件正常工作。 I am currently using this code but it is not working 我目前正在使用此代码,但无法正常工作
<!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>
And i am using this XML code 我正在使用此XML代码
<?xml version="1.0" encoding="UTF-8"?>
<e-mail>
<to>John</to>
<from>Larry</from>
<message>Hello how are you!</message>
</e-mail>
You are missing closing </h1>
tags, also <h1>
is not valid child of <p>
element; 您缺少关闭</h1>
标记,而且<h1>
不是<p>
元素的有效子元素; use .onload
event of XMLHttpRequest()
to perform tasks with .responseText
; 使用XMLHttpRequest()
.onload
事件通过.responseText
执行任务; add index [0]
following getElementsByTagName()
call to reference specific element in HTMLCollection
在调用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 plnkr https://plnkr.co/edit/jLsO3SgV8dMG3sRBZbds?p=preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.