You can work with the DOM API directly.  DOM is a portable API that is a W3C
standard, and pretty much the same in every language.  But it is not
especially compact.  There is a simplified API, JDOM, which you might like
better (www.jdom.org) but it is not a core part of the Java platform.  There
are many sources on the Web that teach both the DOM and JDOM APIs, but here
is the beginning of an implementation for your example document:

// obtain a new DOM Document using the JAXP Document Builder factory
mechanism
Document doc = DocumentBuilderFactory.newDocumentBuilder().newDocument();
// create elements: there must be a single root element
Element rootElement = doc.createElement("service");
doc.appendChild(rootElement);
Element types = doc.createElement("Types");
rootElement.appendChild(types);
// add attributes
types.setAttribute("name","typeA");
// ... continue fully populating your document, attaching each element or
text node to its parent

The main advantage to using DOM or JDOM to create a response, as opposed to
just building an XML string directly, is that the DOM API will automatically
take care of correctness issues for you; for example, if you include text
that contains < or > characters, these will be transformed to &lt; and &gt;
so that your document remains well-formed.  The disadvantage is that a DOM
structure is built in memory and is large and slow compared to a
StringBuffer.  So this approach is not good for massive XML documents (say,
more than 250K).  It is safest to avoid massive XML documents altogether
until/unless you are really, really comfortable with all the different means
of handling XML and their side effects.

Anyway, once you have a DOM Document, you can just use the DomRepresentation
of Restlet:

DomRepresentation rep = new DomRepresentation(MediaType.TEXT_XML,doc);

Return this from the represent(...) method of a Resource or, in a Restlet's
handle method, say response.setEntity(rep);  You don't need to worry about
the transformation stuff previously described; Restlet will do this for you.

- R


On Fri, Mar 14, 2008 at 11:53 PM, Leshek <[EMAIL PROTECTED]> wrote:

> I know how I want my XML representation to look.  I can easily (?:-)
>  craft it by StringBuffer, but... would really like to take advantage of DOM
> and Restlet.
> What is the best way to build, manipulate and return representation like
> the following (all, other comments also welcome):
>
> <?xml version="1.0" encoding="ASCII"?>
> <service>
>   <Types name="typeA" description="typeA description">
>     <attributeNames>Name</attributeNames>
>   </Types>
>   <Types name="type2" description="type2">
>     <attributeNames>Name</attributeNames>
>     <attributeNames>ContainerName</attributeNames>
>     <relationshipNames>Contains</relationshipNames>
>     <relationshipNames>ContainedIn</relationshipNames>
>   </Types>
> </service>
>

Reply via email to