All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.rathravane.till.data.xml.rrXmlWriteHelper Maven / Gradle / Ivy

There is a newer version: 2.1.1
Show newest version
package com.rathravane.till.data.xml;

import java.util.Map;

import com.rathravane.till.data.rrConvertor;

public class rrXmlWriteHelper
{
	public static String wrapInElement ( String tag, String text )
	{
		return makeElement ( tag, false ) +
			xmlEncode ( text ) +
			makeElement ( tag, true );
	}

	public static String makeElement ( String tag, boolean closing )
	{
		return "<" + (closing?"/":"") + xmlEncode ( tag ) + ">";
	}

	public static String openElement ( String tag )
	{
		return makeElement ( tag, false );
	}

	public static String closeElement ( String tag )
	{
		return makeElement ( tag, true );
	}

	public static String makeElement ( String tag, Map attrs )
	{
		final StringBuffer sb = new StringBuffer ();
		sb.append ( "<" );
		sb.append ( xmlEncode ( tag ) );
		sb.append ( " " );
		for ( Map.Entry e : attrs.entrySet () )
		{
			sb.append ( xmlEncode(e.getKey ()) );
			sb.append ( "=\"" );
			sb.append ( xmlEncode(e.getValue ()) );
			sb.append ( "\" " );
		}
		sb.append ( ">" );
		return sb.toString ();
	}

	public static String xmlEncode ( String s )
	{
		String result = null;
		if ( s != null )
		{
			StringBuffer sb = new StringBuffer ();
			for ( int i=0; i': sb.append ( ">" ); break;
					case '&': sb.append ( "&" ); break;
					case '\'': sb.append ( "'" ); break;
					case '\n': sb.append ( "
" ); break;
					case '\r': sb.append ( "
" ); break;
					default: sb.append ( c ); break;
				}
			}
			result = sb.toString ();
		}
		return result;
	}

	public static String xmlDecode ( String s )
	{
		String result = null;
		if ( s != null )
		{
			StringBuffer sb = new StringBuffer ();
			for ( int i=0; i' );
						i += 3;
					}
					else if ( i+5 < s.length () && s.substring(i).startsWith ( "&" ) )
					{
						sb.append ( '&' );
						i += 4;
					}
					else if ( i+6 < s.length () && s.substring(i).startsWith ( "'" ) )
					{
						sb.append ( '\'' );
						i += 5;
					}
					else if ( i+6 < s.length () && s.substring(i).startsWith ( " " ) )
					{
						sb.append ( ' ' );
						i += 5;
					}
					else if ( i+1 < s.length () && s.substring (i).startsWith ( "&#" ) )
					{
						try
						{
							// unicode char
							final int semi = s.indexOf ( ';', i );
							final String chunk = s.substring(i+2,semi);
							i=semi;
							int value = 0;
							for ( char digit : chunk.toCharArray () )
							{
								value *= 10;
								value += rrConvertor.charToNibble ( digit );
							}
							sb.append ( Character.toChars ( value ) );
						}
						catch ( rrConvertor.conversionError e )
						{
							sb.append ( "??" );
						}
					}
				}
				else
				{
					sb.append ( c );
				}
			}
			result = sb.toString ();
		}
		return result;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy