cocoon-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Simone Tripodi <simonetrip...@apache.org>
Subject potential SAX builder helper class
Date Mon, 23 Apr 2012 14:35:33 GMT
Hi all guys,

One thing I've always found a little "annoying" - "boring" is maybe
the more appropriate therm - of SAX APIs is that, when crating even
simple XML snippets via ContentHandler APIs, the following boilerplate
code has to be written:

+--------+
ContentHandler handler = ... ;
contentHandler.startDocument();
contentHandler.startElement( "", "project", "project", new AttributesImpl() );
contentHandler.startElement( "", "modelVersion", "modelVersion", new
AttributesImpl() );

String modelVersion = "4.0.0";
contentHandler.characters( modelVersion.toCharArray(), 0,
modelVersion.length() );

contentHandler.endElement( "", "modelVersion", "modelVersion" );
contentHandler.endElement( "", "project", "project", new AttributesImpl() );
contentHandler.endDocument();
+--------+

I think you would agree with me that to obtain the following snippet

+--------+
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <modelVersion>4.0.0</modelVersion>
</project>
+--------+

that code is maybe an overkill :P

So, at company I developed a small SAX wrapper that would help on
transforming the previous code in the following:

+--------+
ContentHandler handler = ... ;
SAXEventsBuilder.newDocument( transformerHandler )
    .start( "project" )
        .start( "modelVersion" ).body( "4.0.0" ).end()
    .end()
.endDocument();
+--------+

isn't more "sexy"? It still supports elements that require
namespaces/attributes but reduces the lines of code for hardcoded XML
documents - especially when closing elements.

It also allows users to add manually-generated elements in an existing
ContentHandler:
+--------+
ContentHandler handler = ... ;
SAXEventsBuilder.wrap( transformerHandler )
    .start( "modelVersion" ).body( "4.0.0" ).end()
    .start( "groupId" ).body( "org.apache.cocoon.sax" ).end()
    .start( "artifactId" ).body( "cocoon-sax" ).end()
    .start( "version" ).body( "3.0.0-beta-1" ).end()
+--------+

without starting/closing the document.

If you like it, I would be pleased to commit it in the Cocoon repo -
as a side question: which component that would fill?

Many thanks in advance, all the best!
-Simo

http://people.apache.org/~simonetripodi/
http://simonetripodi.livejournal.com/
http://twitter.com/simonetripodi
http://www.99soft.org/

Mime
View raw message