ESQL Taglib

Implementing the org.apache.cocoon.xml.XMLFragment interface

An XMLFragment is an object that can be represented as a XML document fragment. The main purpose of this standard interface is to provide a uniform way of inserting dynamically-generated XML into XSP pages. See the relevant FAQ for more details and alternatives.

As described in the Javadoc documentation, the toDOM() method (used by Cocoon 1) should append the XML representation of the object as children of the given node, and the toSAX() method (used by Cocoon 2) should generate the XML representation as SAX events.

A typical XMLFragment implementation might look like this:

  public class FragmentTest implements XMLFragment
  {
    public void toDOM(Node node)
    {
      Document doc = node.getOwnerDocument();
      Element e = doc.createElement("foo");
      e.appendChild(doc.createTextNode("bar"));
      node.appendChild(e);
    }

    public void toSAX(ContentHandler handler)
    {
      AttributesImpl attr = new AttributesImpl();
      handler.startElement("","foo","foo",attr);

      String content = "bar";
      handler.characters(content.toCharArray(), 0, content.length());

      handler.endElement("","foo","foo");
    }
  }

Both methods result in <foo>bar</foo> being inserted in the resulting document.

Of course, it is very wasteful to write two methods to do exactly the same thing! That is why we suggest people implement only toSAX directly, and then form a DOM tree from the SAX events in the toDOM method. An XMLFragmentBase class is in development to simplify this.