1 8 package org.codehaus.dna.impl; 9 10 import org.codehaus.dna.Configuration; 11 import org.xml.sax.ContentHandler ; 12 import org.xml.sax.SAXException ; 13 import org.xml.sax.helpers.AttributesImpl ; 14 15 22 public class SAXConfigurationSerializer 23 { 24 27 private static final String CDATA_TYPE = "CDATA"; 28 29 32 private static final String EMPTY_NAMESPACE = ""; 33 34 37 39 42 44 53 public void serialize( final Configuration configuration, 54 final ContentHandler handler ) 55 throws SAXException 56 { 57 handler.startDocument(); 58 serializeElement( configuration, handler ); 59 handler.endDocument(); 60 } 61 62 70 void serializeElement( final Configuration configuration, 71 final ContentHandler handler ) 72 throws SAXException 73 { 74 final AttributesImpl attributes = serializeAttributes( configuration ); 75 76 final String name = configuration.getName(); 77 handler.startElement( EMPTY_NAMESPACE, name, name, attributes ); 78 79 String value = configuration.getValue( null ); 80 if( null == value ) 81 { 82 final Configuration[] children = configuration.getChildren(); 83 for( int i = 0; i < children.length; i++ ) 84 { 85 serializeElement( children[ i ], handler ); 86 } 87 } 88 else 89 { 90 95 handler.characters( value.toCharArray(), 0, value.length() ); 96 } 97 98 handler.endElement( EMPTY_NAMESPACE, name, name ); 99 } 100 101 107 AttributesImpl serializeAttributes( final Configuration configuration ) 108 { 109 final AttributesImpl attributes = new AttributesImpl (); 110 final String [] names = configuration.getAttributeNames(); 111 for( int i = 0; i < names.length; i++ ) 112 { 113 final String name = names[ i ]; 114 final String value = configuration.getAttribute( name, "" ); 115 attributes.addAttribute( EMPTY_NAMESPACE, name, name, 116 CDATA_TYPE, value ); 117 } 118 return attributes; 119 } 120 121 128 134 } 135 | Popular Tags |