SAX Parse with Apache Commons Digester

Pēdējais mainījis superadmin 2018-01-12 21:33

SAX Parse with Apache Commons Digester

Public source: http://java-eim.googlecode.com/svn/trunk/java-eim-demo-digester Local source: /home/student/workspace/java-eim-demo-digester Technologies: Java (J2SDK 1.6), Ant and Maven2 build tools, JDeveloper IDE, Xerces XML library, Commons Digester Estimated time: 15 minutes

Parsing is the process of reading the XML data and transforming it into something else. Since all XML data has the same basic syntax, using XML means that we can use pre-built parsers (rather than writing our own parsers). For simple and highly regular XML data the most useful parsers are event-based (SAX) parsers. Since low-level SAX generates too many events, there are rule-based parsing mechanisms that work on top of SAX. One of such libraries is Apache Commons Digester - frequently used to read config-files and other data with predictable structure in J2EE applications. 

General Description and Scope

Given a code sample to parse XML data, modify it (add new rules) to extract more information.

Provided resources

 

  • Apache Commons Digester code sample
  • Ant script or JDeveloper to run the application as a main method
  • JUnit test to check the correctness of the parsing

Activities

  • Run the provided application - run the ModuleDigesterTest as a JUnit testcase; see what is printed to the console; and the two failed testcases (one of them is called "Failure", another is called "Error"). 
  • Open commandline and type these commands:
cd /home/student/workspace/java-eim-demo-digester
mvn jetty:run
  • Open the URL http://localhost:9080/digester/servlet/DigesterDemoServlet to see the parsed Java objects being displayed (after submitting the Web form). Notice that test questions do not have variants, even though the variants are provided in the XML data being submitted.
  • To parse the answer variants as well, add a few more parsing rules to the class ModuleDigester.java so that all asserts are satisfied and JUnit tests run successfully. There are 4 new rules to the digester:

    digester.addObjectCreate("module/question/variants/var", Variant.class);
    digester.addCallMethod("module/question/variants/var", "setValue", 0);
    digester.addSetProperties("module/question/variants/var");
    digester.addSetNext("module/question/variants/var", "addVariant");
    
  • Run the JUnit test suite again; also try the Web application (if you have not closed the console, it is likely that Jetty Web server has reloaded the changed Java application)
Izveidojis Kalvis Apsītis 2007-10-14 12:37
    
This wiki is licensed under a Creative Commons 2.0 license
XWiki Enterprise 6.4 - Documentation