我在arraylist中有大约3000个元素。需要将这3000个元素写入xml。执行花费了太多时间,例如 Eclipse 中的 20 分钟。有没有有效的方法来做到这一点?或对我的代码进行任何修改?
arraylist 中的元素应该在未来增长......
我的代码片段..
---------------------------------------------------
---------------------------------------------------
for(int i=0;i<candidates.size();i++)//Candidates is my arraylist
{
String text=candidates.get(i);
//System.out.println(text);
text=text+"\n";
file= new File("./test.xml");
WriteToXML wr= new WriteToXML(file,"fullname",text);
}
-------------------------------------------------------
-------------------------------------------------------
//WritetoXML class constructor
public WriteToXML(File xml,String tag,String data)
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(new File(xml)));
Element element = doc.getDocumentElement();
NodeList node1 = doc.getElementsByTagName(tag);
Element fn= (Element) node1.item(0);
Text text = doc.createTextNode(data);
fn.appendChild(text);
printtoXML(doc);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static final void printtoXML(Document xml) throws Exception {
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(xml);
tf.transform(source, result);
String xmlString = sw.toString();
File file= new File(xml);
FileWriter fw=new FileWriter(file,false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(xmlString);
bw.flush();
bw.close();
}