Tuesday, January 6, 2009

XML Friendly Pages

Now, this post was intended to solve a problem that i faced while blogging. As you see, i post code snippets in this blog. However, since my code can sometimes contain XML unfriendly characters like < and > so i had to find a way around it. Well, i tried using CDATA as well, but google just wont let me post. The savvy programmer that i am , i decided to make a simple and short program to find way around this.
What i did was that i made a program that would replace the above mentioned XML unfriendly characters from my source file into XML friendly ones.

This program takes an argument a file that needs to be converted.

The code goes as follows:

MakeXmlFriendly.java

//--------Start of source code----------------
import java.io.*;

public class MakeXmlFriendly
{
static File inputFile;
static File outputFile;
static StringBuffer inputFileBuffer;
static StringBuffer outputFileBuffer;


public static void main(String [] args) throws IOException
{
if(args!=null&& args.length>0)
{
inputFile=new File(args[0]);
outputFile= new File("XmlFriendly"+args[0]);

inputFileBuffer=new StringBuffer();
outputFileBuffer=new StringBuffer();

BufferedReader inputFileReader=new BufferedReader(new FileReader(args[0]));
BufferedWriter outputFileWriter =new BufferedWriter(new FileWriter(outputFile));

String separator=System.getProperty("line.separator");


String line=inputFileReader.readLine();
while(line!=null)
{
System.out.print(line);
outputFileBuffer.append(line);
outputFileBuffer.append(separator);
line=inputFileReader.readLine();
}


String replaceString=outputFileBuffer.toString();
System.out.print(replaceString);
replaceString=replaceString.replaceAll("<", "&lt;");
replaceString=replaceString.replaceAll(">", "&gt;");

outputFile.createNewFile();

outputFileWriter.write(replaceString);
outputFileWriter.flush();
outputFileWriter.close();
}
}
}

//--------End of source code---------------

With little more improvement, i suppose that it will come in quite handy.

Happy Programming ;)

Signing Off
Ryan

No comments: