java 使用 jdom 向现有 xml 添加内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15209245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:51:43  来源:igfitidea点击:

adding content to existing xml with jdom

javaxmlclassdocumentjdom

提问by Boyen

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();
        }
    }
}

This is my class for writing an xml file with variables from my main class. The output here would be :

这是我的类,用于使用我的主类中的变量编写 xml 文件。这里的输出将是:

http://pastebin.com/nFtiv2b8

http://pastebin.com/nFtiv2b8

Now I have a problem, the next time I run this java application I want it to add a new product but keep the old one. However every time I try this, it replaces the old data with the new data.

现在我遇到了一个问题,下次我运行这个 java 应用程序时,我希望它添加一个新产品但保留旧产品。但是,每次我尝试这样做时,它都会用新数据替换旧数据。

回答by A4L

Basically, you need to load an existing xml file and make a Documentof it by parsing it and getting the root element from it. If the file does not exist then create a new document and a new root element. After that you can go on with the code you have shown.

基本上,您需要加载一个现有的 xml 文件并Document通过解析它并从中获取根元素来制作它。如果该文件不存在,则创建一个新文档和一个新的根元素。之后,您可以继续使用您显示的代码。

Create a class Productto hold product data. Passing product data each as argument to a method is a no-go.

创建一个类Product来保存产品数据。将每个产品数据作为参数传递给方法是不行的。

Product class (for simplicity all fields are public, this not a good practice, you should make them at least protected and for each a getter and a setter method)

产品类(为简单起见,所有字段都是公开的,这不是一个好习惯,您应该至少使它们受保护,并为每个字段设置一个 getter 和一个 setter 方法)

public class Product {
    public String categorie;
    public String code;
    public String naamartikel;
    public String beschrijvingartikel;
    public double prijz;
    public String imgurl;
    public String imgurl2;
    public String imgurl3; 
    public String imgurl4;
    public String imgurl5;
}

Writer method

写法

public static void Writer(Product product) throws JDOMException, IOException {

    Document document = null;
    Element root = null;

    File xmlFile = new File("products.xml");
    if(xmlFile.exists()) {
        // try to load document from xml file if it exist
        // create a file input stream
        FileInputStream fis = new FileInputStream(xmlFile);
        // create a sax builder to parse the document
        SAXBuilder sb = new SAXBuilder();
        // parse the xml content provided by the file input stream and create a Document object
        document = sb.build(fis);
        // get the root element of the document
        root = document.getRootElement();
        fis.close();
    } else {
        // if it does not exist create a new document and new root
        document = new Document();
        root = new Element("productlist");
    }


    String prijs = String.valueOf(product.prijz);
    String naamelement = "naam";
    String categorieelement = "category";
    String descriptionelement = "description";
    Element child = new Element("product");
    child.addContent(new Element(categorieelement).setText(product.categorie));
    child.addContent(new Element("code").setText(product.code));
    child.addContent(new Element(naamelement).setText(product.naamartikel));
    child.addContent(new Element(descriptionelement).setText(product.beschrijvingartikel));
    child.addContent(new Element("price").setText(prijs));
    child.addContent(new Element("image").setText(product.imgurl));
    child.addContent(new Element("image").setText(product.imgurl2));
    child.addContent(new Element("image").setText(product.imgurl3));
    child.addContent(new Element("image").setText(product.imgurl4));
    child.addContent(new Element("image").setText(product.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);
        writer.close(); // close writer
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and finally a little test

最后是一个小测试

public static void main(String[] args) throws JDOMException, IOException {
    Product product = null;

    product = new Product();
    product.categorie = "cat1";
    product.code = "code1";
    product.naamartikel = "naam1";
    product.beschrijvingartikel = "beschrijving1";
    product.prijz = 100d;
    product.imgurl = "http://localhost/img1.png";
    product.imgurl2 = "http://localhost/img2.png";
    product.imgurl3 = "http://localhost/img3.png";
    product.imgurl4 = "http://localhost/img5.png";
    product.imgurl5 = "http://localhost/img5.png";
    Writer(product);

    product = new Product();
    product.categorie = "cat2";
    product.code = "code2";
    product.naamartikel = "naam2";
    product.beschrijvingartikel = "beschrijving2";
    product.prijz = 200d;
    product.imgurl = "http://localhost/img21.png";
    product.imgurl2 = "http://localhost/img22.png";
    product.imgurl3 = "http://localhost/img23.png";
    product.imgurl4 = "http://localhost/img25.png";
    product.imgurl5 = "http://localhost/img25.png";
    Writer(product);

    product = new Product();
    product.categorie = "cat3";
    product.code = "code3";
    product.naamartikel = "naam3";
    product.beschrijvingartikel = "beschrijving3";
    product.prijz = 300d;
    product.imgurl = "http://localhost/img31.png";
    product.imgurl2 = "http://localhost/img32.png";
    product.imgurl3 = "http://localhost/img33.png";
    product.imgurl4 = "http://localhost/img35.png";
    product.imgurl5 = "http://localhost/img35.png";
    Writer(product);
}

Also, file name products.xmlshould not be hard coded in java file; instead pass it as an argument when you run the program.

此外,文件名products.xml不应硬编码在 java 文件中;而是在运行程序时将其作为参数传递。

回答by gxet4n

Replace root=document.getRootElement();by

替换root=document.getRootElement();

root = document.detachRootElement();

because an Element can be associated to only one document in jdom.

因为一个 Element 在 jdom 中只能关联到一个文档。

回答by gxet4n

Before setting root as the content of document use:

在将 root 设置为文档内容之前使用:

root = root.detach();

because an Element can be associated to only one document in jdom.

因为一个 Element 在 jdom 中只能关联到一个文档。