commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Maciek Kolesnik <mkoles...@gmail.com>
Subject [betwixt] serialization to DOM rather than string
Date Fri, 14 Oct 2005 18:11:10 GMT
Submitting this just for consideration ....

This version of BeanWriter will serialize an object graph as DOM as oppose
to string. Might be useful in some cases.



package COM.soundbite.xml.serialization;

import java.io.IOException;
import java.util.Stack;

import org.apache.commons.betwixt.XMLUtils;
import org.apache.commons.betwixt.io.WriteContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

/**
* A class that overrides standard behaviour of the betwixt by serializing
into DOM rather than string
*
* @author mkolesnik
* @version $Id: $
*
*/
public class DOMBeanWriter extends BeanWriter {

private Element rootElement;
private Document rootDocument;
private Stack elements = new Stack();

/**
* creates new instance of the writer that will create DOM rooted at
* the element passed in
* @param root root element to append the rest to.
*/
public DOMBeanWriter(Element root) {
rootDocument = root.getOwnerDocument();
rootElement = root;
}

/**
* creates new instance of the writer that will create DOM starting from the
root node passed in
* @param root root element to append the rest to.
*/
public DOMBeanWriter(Document root) {
rootDocument = root;
}

public void start() throws IOException, SAXException {
if (rootElement != null) {
elements.push(rootElement);
} else {
elements.push(rootDocument);
}
}

public void end() throws IOException, SAXException {
elements.pop();
}

protected void startElement(WriteContext context, String uri, String
localName, String qualifiedName, Attributes attr)
throws IOException, SAXException {

Node parent = (Node) elements.peek();
Element currentElement = rootDocument.createElement(localName);

parent.appendChild(currentElement);
elements.push(currentElement);

for (int i = 0; i < attr.getLength(); i++) {
currentElement.setAttribute(attr.getQName(i), XMLUtils.escapeAttributeValue(
attr.getValue(i)));
}
}

protected void endElement(WriteContext context, String uri, String
localName, String qualifiedName)
throws IOException, SAXException {

elements.pop();
}


protected void bodyText(WriteContext context, String text) throws
IOException {

Node currentElement = (Node) elements.peek();

Node newElement = rootDocument.createTextNode(
getMixedContentEncodingStrategy().encode(
text,
context.getCurrentDescriptor()));

currentElement.appendChild(newElement);

}

}

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message