我有一个带有 xml 文件的 Web 服务器,该文件有时会保存网站上帖子的信息。这是xml的结构。
<?xml version="1.0" encoding="ISO-8859-1"?>
<posts>
<post>
<date>7/9/2013 6:44 PM</date>
<category>general</category>
<poster>elfenari</poster>
<title>Test Post</title>
<content>This is a test post for the website</content>
</post>
</posts>
我在netbeans 中使用swing 创建了一个小程序,用它作为从小程序中的UI 对象创建xml 的代码。
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document doc = docBuilder.parse(url.openStream());
Element root = doc.getDocumentElement();
Element ePost = doc.createElement("post");
Element eDate = doc.createElement("date");
eDate.setTextContent(time);
Element eCategory = doc.createElement("category");
eCategory.setTextContent(category);
Element eTitle = doc.createElement("title");
eTitle.setTextContent(title);
Element ePoster = doc.createElement("poster");
ePoster.setTextContent(poster);
Element eContent = doc.createElement("content");
eContent.setTextContent(post);
ePost.appendChild(eDate);
ePost.appendChild(eCategory);
ePost.appendChild(eTitle);
ePost.appendChild(ePoster);
ePost.appendChild(eContent);
root.appendChild(ePost);
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
OutputStream f0;
byte buf[] = xmlString.getBytes();
f0 = new FileOutputStream(url);
for(int i=0;i<buf .length;i++) {
f0.write(buf[i]);
}
f0.close();
buf = null;
} catch (TransformerException ex) {
Logger.getLogger(xGrep.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException | SAXException | IOException ex) {
Logger.getLogger(xGrep.class.getName()).log(Level.SEVERE, null, ex);
}
}
我已经做了一些研究,我认为我的服务器上需要一个 java 程序来接受对 xml 的更改,但我不确定该怎么做。你能告诉我在服务器上编辑文件需要什么,以及如果我确实需要如何编写代码吗?