fork download
  1. import java.io.*;
  2. import java.util.*;
  3. import javax.xml.parsers.*;
  4. import org.xml.sax.*;
  5. import org.xml.sax.helpers.*;
  6.  
  7. class MyHandler extends DefaultHandler {
  8. private List<String> values = new ArrayList<String>();
  9. private String currentTag = "";
  10. @Override public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) {
  11. if(qName.equals("cons")) {
  12. String value = attrs.getValue("cat");
  13. values.add(value);
  14. System.out.println(f(values));
  15. currentTag = qName;
  16. } else if(qName.equals("tok")) {
  17. String value = attrs.getValue("pos");
  18. values.add(value);
  19. System.out.print(f(values));
  20. currentTag = qName;
  21. }
  22. }
  23. @Override public void endElement(String namespaceURI, String localName, String qName) {
  24. if(qName.equals("cons") || qName.equals("tok")) {
  25. int sz = values.size();
  26. values.remove(sz-1);
  27. System.out.println(f(values));
  28. }
  29. currentTag = "";
  30. }
  31. @Override public void characters(char[] ch, int start, int length) {
  32. if(currentTag.equals("tok")) {
  33. String str = new String(ch, start, length);
  34. if(str.length() > 0) { System.out.println(" " + str); }
  35. }
  36. }
  37. private String f(List<String> strs) {
  38. StringBuilder res = new StringBuilder("[");
  39. for(String str : strs) { res.append(str + ", "); }
  40. int sz = res.length();
  41. if(sz > 2) { res.delete(sz-2, sz); }
  42. res.append("]");
  43. return res.toString();
  44. }
  45. }
  46.  
  47. public class Main {
  48. public static void main(String[] args) {
  49. try {
  50. SAXParserFactory factory = SAXParserFactory.newInstance();
  51. SAXParser parser = factory.newSAXParser();
  52. MyHandler handler = new MyHandler();
  53. parser.parse(new FileInputStream("parse.xml"), handler);
  54. } catch(Exception ex) {
  55. ex.printStackTrace();
  56. }
  57. }
  58. }
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty