package xml.dierenshop.flaming.v1;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
import org.jdom2.output.Format;
import java.io.FileWriter;
import java.io.IOException;
public class Writer {
public void Writer(String categorie, String code, String naamartikel, String beschrijvingartikel, double prijz, String imgurl, String imgurl2, String imgurl3, String imgurl4, String imgurl5) {
String prijs = String.valueOf(prijz);
Document document = new Document();
Element root = new Element("productlist");
String naamelement = "naam";
String categorieelement = "category";
String descriptionelement = "description";
Element child = new Element("product");
child.addContent(new Element(categorieelement).setText(categorie));
child.addContent(new Element("code").setText(code));
child.addContent(new Element(naamelement).setText(naamartikel));
child.addContent(new Element(descriptionelement).setText(beschrijvingartikel));
child.addContent(new Element("price").setText(prijs));
child.addContent(new Element("image").setText(imgurl));
child.addContent(new Element("image").setText(imgurl2));
child.addContent(new Element("image").setText(imgurl3));
child.addContent(new Element("image").setText(imgurl4));
child.addContent(new Element("image").setText(imgurl5));
root.addContent(child);
document.setContent(root);
try {
FileWriter writer = new FileWriter("products.xml");
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(document, writer);
outputter.output(document, System.out);
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是我用我的主类写变量的xml文件的类。 这里的输出是:使用jdom将内容添加到现有的xml
现在我有一个问题,下一次我运行这个Java应用程序,我希望它添加一个新的产品,但保留旧的。但是,每次我尝试这种方法时,都会用新数据替换旧数据。
请在这里发布你的代码。 – bsiamionau 2013-03-04 19:23:40
我真诚的道歉,我真的不明白如何做到这一点在stackoverflow。 – Boyen 2013-03-04 19:24:23
当我这样做时,有一个名为“代码示例”的问题表单中的特殊按钮'(Ctrl + K)' – bsiamionau 2013-03-04 19:26:36