package org.bodington.xml;

public class XMLUtils
	{
	public static char[] illegalPCDataChars = 
		{ '<', '>', '&',  };
		
	public static String[] pcDataEscapes = 
		{ "&lt;", "&gt;", "&amp;",  };
		
	public static char[] illegalAttributeChars = 
		{ '<', '>', '&', '\'', '"' };

	public static String[] attributeEscapes = 
		{ "&lt;", "&gt;", "&amp;", "&apos;", "&quot;" };
		

	private static boolean needsEscaping( String str, char[] illegalChars )
		{
		for ( int j=0; j< illegalChars.length; j++ )
			if ( str.indexOf( illegalChars[j] ) >=0 )
				return true;
				
		return false;
		}

	private static String escapeString( String str, char[] illegalChars, String[] escapes )
		{
		if ( !needsEscaping( str, illegalChars ) )
			return str;
		
		StringBuffer output = new StringBuffer( ((str.length() * 10) / 16)+1 );
		int i, j;
		
		for ( i = 0; i<str.length(); i++ )
			{
			for ( j=0; j< illegalChars.length; j++ )
				{
				if ( illegalChars[j] == str.charAt( i ) )
					break;
				}
				
			if ( j<illegalChars.length )
				output.append( escapes[j] );
			else
				output.append( str.charAt( i ) );
			}
			
		return output.toString();
		}
		

	public static String toPCData( String str )
		{
		return escapeString( str, illegalPCDataChars, pcDataEscapes );
		}
		
	public static String toAttribute( String str )
		{
		return escapeString( str, illegalAttributeChars, attributeEscapes );
		}
	
	}
