XMLFragment Interface
http://xml.apache.org/http://www.apache.org/http://www.w3.org/

Back

Download

Index
License

Install

Technologies
Infrastructure
User Guide
Dynamic XML
Caching
How it works
XML Links

XSP Processor
XSP WD
XMLFragments
ESQL Taglib
SQL Conn Pool
FP Taglib
LDAP Processor

SQL Processor
SQL Taglib

Contributing
3rd Party
Patch Queue

FAQ
Changes
Todo

Live Sites
Cocoon Hosting

Bug Database
Code Repository
Mail Lists
Mail Archives

Cocoon 2.0 Site
Cocoon 2.1 Site


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");
    }
  }

To insert a FragmentTest you might do something like this (if myMethod() returns a FragmentTest):

  <xsp:expr>MyClass.myMethod()</xsp:expr>

Both methods in the example above 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.


Copyright © 1999-2001 The Apache Software Foundation. All Rights Reserved.