Mega Code Archive

 
Categories / Java / XML
 

Reading an XML Document and create user-defined object from DOM

import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; public class ListMoviesXML {   public static void main(String[] args) throws Exception {     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();     factory.setIgnoringComments(true);     factory.setIgnoringElementContentWhitespace(true);     factory.setValidating(true);     DocumentBuilder builder = factory.newDocumentBuilder();     Document doc = builder.parse(new InputSource("y.xml"));     Element root = doc.getDocumentElement();     Element movieElement = (Element) root.getFirstChild();     Movie m;     while (movieElement != null) {       m = getMovie(movieElement);       String msg = Integer.toString(m.year);       msg += ": " + m.title;       msg += " (" + m.price + ")";       System.out.println(msg);       movieElement = (Element) movieElement.getNextSibling();     }   }   private static Movie getMovie(Element e) {     String yearString = e.getAttribute("year");     int year = Integer.parseInt(yearString);     Element tElement = (Element) e.getFirstChild();     String title = getTextValue(tElement).trim();     Element pElement = (Element) tElement.getNextSibling();     String pString = getTextValue(pElement).trim();     double price = Double.parseDouble(pString);     return new Movie(title, year, price);   }   private static String getTextValue(Node n) {     return n.getFirstChild().getNodeValue();   } } class Movie {   public String title;   public int year;   public double price;   public Movie(String title, int year, double price) {     this.title = title;     this.year = year;     this.price = price;   } }