JPz'log Coin Coin and Plop da Plop

15Aug/050

Dom4J rulez

In case you would still be having fun with the standard J2SE DOM/SAX APIs, I suggest that you take a look at the Dom4J API. Not only the API is a breeze to use, but it really enhances your XML productivity. It has an DOM-integrated XPath support (through Jaxen), making things really powerful. I have started playing with it this morning and got converted a SAX + hand-crafted XML generation to using Dom4J by the beginning of the afternoon.

Here are some code extracts:

Reading

// Parsing SAXReader saxReader = new SAXReader(); Document document = saxReader.read(reader); // Protocol BusinessProtocol protocol = factory.createBusinessProtocol(document     .valueOf("/business-protocol/name")); //$NON-NLS-1$ readExtraProperties(protocol, document.selectSingleNode("/business-protocol")); //$NON-NLS-1$

Writing

// States Iterator it = protocol.getStates().iterator(); while (it.hasNext()) {     State s = (State) it.next();     Element el = root.addElement("state"); //$NON-NLS-1$     el.addElement("name").setText(s.getName()); //$NON-NLS-1$     el.addElement("final").setText(s.isFinalState() ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$     if (s.isInitialState())     {         el.addElement("initial-state"); //$NON-NLS-1$     }     writeExtraProperties(el, s); } // States Map states = new HashMap(); it = document.selectNodes("/business-protocol/state").iterator(); //$NON-NLS-1$ while (it.hasNext()) {      node = (Node) it.next();       State s = factory.createState(node.valueOf("name"), "true" //$NON-NLS-1$ //$NON-NLS-2$           .equals(node.valueOf("final"))); //$NON-NLS-1$       readExtraProperties(s, node);       protocol.addState(s);       states.put(s.getName(), s);       if (node.selectSingleNode("initial-state") != null) //$NON-NLS-1$       {            protocol.setInitialState(s);       } }
Share this post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Live
  • Netvibes
  • StumbleUpon
  • Technorati
  • FriendFeed
  • Wikio
  • Twitter
  • Identi.ca
  • Reddit
  • RSS
  • Slashdot

Related posts:

  1. Save time, use JXPath
  2. Discovering Grails Web Flows
  3. Handling file uploads with the Google Web Toolkit
  4. Apple rulez
  5. FreeBSD rulez

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.

JPz'log is Digg proof thanks to caching by WP Super Cache