[Yanel-dev] DOM Helper classes.
Alec Bickerton
alec.bickerton at wyona.com
Mon Sep 29 11:18:30 CEST 2008
Are there any similar helper classes in the yanel core that include the
functionality shown below.
In short :
- Create a new DOM object
- Create a text element
- Convert a DOM into a String.
Not xml related but useful.
- Stream data
If not, then I would like to include these in a new package under
org.wyona.util...
WDYT?
Code below..
private void streamData( InputStream is, OutputStream os, int
packetSize ) throws IOException {
final byte[ ] packet = new byte[ packetSize ];
int c = 0;
while( ( c = is.read( packet )) != -1 ){
os.write( packet );
}
}
public static final String toString( Document document, boolean
isFragment, boolean indent, String charset ) {
if( document == null )
return null;
StringWriter strWtr = new StringWriter();
StreamResult strResult = new StreamResult(strWtr);
TransformerFactory tfac = TransformerFactory.newInstance();
try {
Transformer t = tfac.newTransformer();
if( isFragment )
t.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, YES );
if( charset == null)
t.setOutputProperty(OutputKeys.ENCODING, DEFAULT_ENCODING);
else
t.setOutputProperty(OutputKeys.ENCODING, charset );
t.setOutputProperty(OutputKeys.INDENT, (indent) ? YES : NO);
t.setOutputProperty(OutputKeys.METHOD, "xml"); //xml, html, text
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
t.transform( new DOMSource(document.getDocumentElement()),
strResult);
} catch (Exception e) {
// todo handle this more specifically
}
return strResult.getWriter().toString();
}
public static final Document createDOM( String rootName ) throws
ParserConfigurationException {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root = doc.createElement( rootName );
doc.appendChild(root);
return doc;
}
public static final Element createTextElement( Document doc, String
name, String value, HashMap<String, String> attribs ){
Element child = doc.createElement( name );
if( attribs !=null ){
Iterator<Entry<String,String>> iter =
attribs.entrySet().iterator();
while( iter.hasNext() ){
Entry<String, String> attr = iter.next();
child.setAttribute( attr.getKey(), attr.getValue() );
}
}
Text text = doc.createTextNode( value );
child.appendChild(text);
return child;
}
More information about the Yanel-development
mailing list