Skip to content

Instantly share code, notes, and snippets.

@Manuri
Last active August 29, 2015 14:23
Show Gist options
  • Save Manuri/9cc837181ce0873a374f to your computer and use it in GitHub Desktop.
Save Manuri/9cc837181ce0873a374f to your computer and use it in GitHub Desktop.
package orderprocessing.service;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import orderprocessing.data.Order;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReaderDOM {
private static XMLReaderDOM instance = null;
private final String savePath;
private XMLReaderDOM(){
savePath="/path/to/orders.xml";
}
public static XMLReaderDOM getInstance() {
if(instance == null){
instance= new XMLReaderDOM();
}
return instance;
}
public Order retrieveOrder(String requiredIndex){
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(savePath);
Element rootElement = doc.getDocumentElement();
NodeList orderList = rootElement.getElementsByTagName("Order");
System.out.println(orderList.getLength());
Node orderElement ;
NodeList children;
int counter;
double price = 0;
String index =null;
for(int i=0;i<orderList.getLength();i++){
orderElement = orderList.item(i);
children = orderElement.getChildNodes();
counter =0;
for(int j=0;j<children.getLength();j++ ){
if(children.item(j).getNodeType()==Node.ELEMENT_NODE){
if(counter==0){
index = children.item(j).getTextContent();
counter++;
}
else
price = Double.parseDouble(children.item(j).getTextContent());
}
}
if(requiredIndex.trim().equals(index)){
return new Order(requiredIndex,price);
}
}
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment