2013-03-04 2 views
3
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-файла с переменными из моего основного класса. Выход здесь будет:добавление содержимого в существующий xml с помощью jdom

http://pastebin.com/nFtiv2b8

Теперь у меня есть проблема, в следующий раз, когда я запустить это приложение Java, я хочу, чтобы добавить новый продукт, но сохранить старый. Однако каждый раз, когда я пытаюсь это сделать, он заменяет старые данные новыми данными.

+0

Пожалуйста, напишите свой код здесь. – bsiamionau

+0

Мои искренние извинения, я действительно не понимаю, как это сделать в stackoverflow. – Boyen

+0

Есть специальная кнопка в форме вопроса с именем «Образец кода» '(Ctrl + K)' – bsiamionau

ответ

6

В принципе, вам необходимо загрузить существующий xml-файл и сделать его Document, проанализировав его и получив из него корневой элемент. Если файл не существует, создайте новый документ и новый корневой элемент. После этого вы можете продолжить код, который вы указали.

Создайте класс Product, чтобы хранить данные о товаре. Передача данных о продуктах в качестве аргумента в метод является не-go.

класс продукции (для простоты все поля являются общедоступными, это не очень хорошая практика, вы должны сделать их, по крайней мере защищены и для каждого добытчика и метод сеттер)

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

метод Писатель

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

и, наконец, небольшой тест

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

Кроме того, имя файла products.xml не должен быть жестко закодирован в java-файле; вместо этого передайте его в качестве аргумента при запуске программы.

+0

Мне удалось выяснить, что-то само собой разумеется в школе, спасибо, хотя! – Boyen

+0

добро пожаловать! – A4L

-3

Перед установкой корня как содержание использования документа:

root = root.detach(); 

, потому что элемент может быть связан только один документ в JDOM.

+0

спасибо за трюки – gxet4n

1

Заменить root=document.getRootElement(); от

root = document.detachRootElement(); 

потому, что элемент может быть связан только с одним документом в JDOM.

Смежные вопросы