我想用一个线程读取一个 XML 文件,并通过 2 个线程向其中添加一些节点。写入线程不能同时写入文件。读取线程读取文件内容并将其放入缓冲区。当读取器执行此操作时,写入器无法访问此缓冲区。
我怎样才能做到这一点??
我以这种方式读取 XML 文件并添加节点:
public synchronized void AddNewNode(Document doc) throws TransformerException {
Element book = doc.createElement("book");
book.setAttribute("id", "3");
Element name = doc.createElement("name");
name.setTextContent("new");
Element id = doc.createElement("id");
id.setTextContent("31");
Element writer = doc.createElement("writer");
writer.setTextContent("tester");
Element price = doc.createElement("price");
price.setTextContent("3100");
book.appendChild(name);
book.appendChild(id);
book.appendChild(writer);
book.appendChild(price);
doc.getDocumentElement().appendChild(book);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult("/home/zahra/workspace/test1/src/xmlfile.xml");
transformer.transform(source, result);
}
public void ReadNodes(Document doc) {
NodeList nList = doc.getElementsByTagName("book");
System.out.println("\n" + ":0 :) :0 :) :0 :) :0 :) :0 :)");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
System.out.println("\n" + "Element number " + (i + 1) + "\n");
Element eElement = (Element) nNode;
for (int j = 0; j < eElement.getChildNodes().getLength(); j++) {
String tagName = eElement.getChildNodes().item(j).getNodeName();
if (eElement.getElementsByTagName(tagName).getLength() > 0) {
System.out.println(eElement.getChildNodes().item(j).getNodeName()
+ " : "
+ eElement.getElementsByTagName(tagName).item(0).getTextContent());
}
}
}
}
谢谢!