Posted By

dalcacer on 03/09/10


Tagged

xml parser sax JDOM


Versions (?)

Basics SAX


 / Published in: Java
 

  1. import java.io.*;
  2. import org.xml.sax.*;
  3. import org.xml.sax.helpers.*;
  4. import org.apache.xerces.parsers.SAXParser;
  5.  
  6.  
  7. public class Flour extends DefaultHandler {
  8.  
  9. float amount = 0;
  10.  
  11. public void startElement(String namespaceURI, String localName,
  12. String qName, Attributes atts) {
  13. if (namespaceURI.equals("http://recipes.org") && localName.equals("ingredient")) {
  14. String n = atts.getValue("","name");
  15. if (n.equals("flour")) {
  16. String a = atts.getValue("","amount"); // assume 'amount' exists
  17. amount = amount + Float.valueOf(a).floatValue();
  18. }
  19. }
  20. }
  21.  
  22. public static void main(String[] args) {
  23. Flour f = new Flour();
  24. SAXParser p = new SAXParser();
  25. p.setContentHandler(f);
  26. try { p.parse(args[0]); }
  27. catch (Exception e) {e.printStackTrace();}
  28. System.out.println(f.amount);
  29. }
  30. }

Report this snippet  

You need to login to post a comment.