java使用jdom向现有xml添加内容
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文件。 这里的输出是:
现在我有一个问题,下次运行这个java应用程序时,我希望它添加一个新产品,但保留旧产品。但是,每次我尝试此操作时,它都会用新数据替换旧数据
# 1 楼答案
用替换
root=document.getRootElement();
因为一个元素只能与jdom中的一个文档关联
# 2 楼答案
基本上,您需要加载一个现有的xml文件,并通过解析它并从中获取根元素来对其进行
Document
。如果文件不存在,则创建一个新文档和一个新的根元素。之后,您可以继续使用显示的代码创建一个类
Product
来保存产品数据。将产品数据作为参数传递给方法是不可能的Product类(为了简单起见,所有字段都是公共的,这不是一个好的实践,您至少应该使它们受到保护,并且对于每个字段都有一个getter和setter方法)
书写方法
最后是一个小测试
此外,文件名
products.xml
不应硬编码到java文件中;而是在运行程序时将其作为参数传递# 3 楼答案
在将根目录设置为文档使用的内容之前:
因为一个元素只能与jdom中的一个文档关联