Скачиваний:
62
Добавлен:
15.06.2014
Размер:
3.05 Кб
Скачать
package workingwithfiles;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import products.BaseProduct;
import datacontainers.BaseProductContainer;

public class BaseProductFileReader {
//constructor
public BaseProductFileReader() {

}

//read information from xml file
public void readFromBaseProductFile(BaseProductContainer baseproductcontainer,String filename) {
//create SAXBuilder object for building Document using a SAX parser
SAXBuilder builder = new SAXBuilder();

//open file using constructor from java.io.File
File xmlFile = new File(filename);

//try read from file information
try {
//create Document object and bind it with our xml file
//where we store information about products
Document document = (Document)builder.build(xmlFile);

//create Element object and get for it root element from our document
Element rootNode = document.getRootElement();

//return the list of all the children elements
//nested directly
List<Element> list = rootNode.getChildren("baseproduct");

//in cicle we parse and enter information from xml file
//in ProductData object
for(int i = 0;i < list.size();i++) {
//create Element object ang get for it element from xml file
//numbered i
Element node = (Element)list.get(i);

//create BaseProduct object for getting data from element
BaseProduct baseproduct = new BaseProduct();

//get info and set it into BaseProduct object
baseproduct.setBaseProductArrivalDate(node.getChildText("arrivaldate"));
baseproduct.setBaseProductCountry(node.getChildText("country"));
baseproduct.setBaseProductMaker(node.getChildText("maker"));
baseproduct.setBaseProductMakerAddress(node.getChildText("makeraddress"));
baseproduct.setBaseProductMakerMail(node.getChildText("makermail"));
baseproduct.setBaseProductMakerPhone(node.getChildText("makerphone"));
baseproduct.setBaseProductWeight(node.getChildText("weight"));
baseproduct.setBaseProductMakerSite(node.getChildText("makersite"));
baseproduct.setBaseProductName(node.getChildText("name"));
baseproduct.setBaseProductNumber(node.getChildText("number"));
baseproduct.setBaseProductPrice(node.getChildText("price"));
baseproduct.setBaseProductShelfLife(node.getChildText("shelflife"));
baseproduct.setBaseProductType(node.getChildText("type"));
baseproduct.setBaseProductDepartment(node.getChildText("department"));

//write BaseProduct object into BaseProductContainer object
baseproductcontainer.addElement(baseproduct);
}
}

catch(IOException ioexception)
{
System.out.println(ioexception.getMessage());
}
catch(JDOMException jdomexception)
{
//try write to log file our problems
System.out.println(jdomexception.getMessage());
}
}
}
Соседние файлы в папке workingwithfiles