我在将 XML 文件加载到网页并显示其中包含的信息时遇到了一个小问题。对于这个程序,我正在尝试使用加载到 XML 文件的恒定数据流来更新一个非常简单的网页。当我的程序找到新数据时(通常每隔几秒一次),它会修改 XML 文件并保存它。另一个 Web 客户端(在 Netbeans 中)运行显示此信息的网页。截至目前,我的问题是当我刷新页面时,没有出现新数据(相同的值仍然存在,即使我知道它们不应该存在)。然后我检查 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();
}
}
}
索引.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>