我在將XML文件加載到網頁並顯示其中包含的信息時遇到了一個小問題。對於這個程序,我試圖用加載到XML文件的恆定數據流更新一個非常簡單的網頁。當我的程序找到新數據(通常每隔幾秒鐘)時,它會修改XML文件並將其保存。另一個Web客戶端(在Netbeans內)運行顯示此信息的網頁。截至目前,我的問題是,當我刷新頁面時,沒有新的數據出現(即使我知道它們不應該是相同的值仍然存在)。然後我檢查XML文件,並且新數據存在,因此它正在成功寫入它。奇怪的是,一旦我打開XML文件來檢查信息,一旦我刷新頁面,網頁將自動更新。這似乎是更新網頁的唯一方法是如果我自己打開xml文件。我的問題是,有人知道發生了什麼,你能提供一種方法來解決這個問題。用XML文件連續更新網頁
我提供我ModifyXML.java代碼和index.jsp頁面以供參考
修改XML
import java.io... //all import statements not shown
public class ModifyXML {
//provide the byte array and the number of the sensor that needs to be
//updated in the XML file
public ModifyXML(byte[] array, int signal) {
try {
//create a new Document Builder to modify the XML file
String filepath = "C:\\user\\projects\\onlineClient\\web\\HTTP.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
// Get the root element
Node Sensor = doc.getFirstChild();
// Get the staff elements by tag name directly
Node data = doc.getElementsByTagName("Data").item(0);
Node data2 = doc.getElementsByTagName("Data2").item(0);
/* Methods to update the information are not shown as they work fine (it saves space)*/
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}
的index.jsp
<html>
<title>Home Monitor Web Client</title>
<body>
<h1>Home Monitor</h1>
<p id="demo">Paragraph.</p>
<p id="demo2">Paragraph.</p>
<br>
<p id="demo3">Paragraph.</p>
<p id="demo4">Paragraph.</p>
<script type="text/javascript">
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","HTTP.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
//document.write("<table border='1'>");
var data=xmlDoc.getElementsByTagName("data");
var data2=xmlDoc.getElementsByTagName("data2");
for (i=0;i<temperature.length;i++)
{
document.getElementById("demo").innerHTML="ID Number: "+data[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
document.getElementById("demo2").innerHTML="Reading: "+data[i].getElementsByTagName("Value")[0].childNodes[0].nodeValue;
document.getElementById("demo3").innerHTML="ID Number: "+data2[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
document.getElementById("demo4").innerHTML="Reading: "+data2[i].getElementsByTagName("Value")[0].childNodes[0].nodeValue;
}
</script>
</body>
</html>