Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help class to filter HTML code

IO / NET

Help class to filter HTML code

by  FredrikN  Posted    (Edited  )
Hi

Lets say you downloaded an html page from www.thegate.nu/uptime.php.

Then the output will look like

-----------------------------------------
<html><head>
<title>Uptime www.thegate.nu</title>
</head>
<body text="#FFFFFF" bgcolor="#000000">

<p align="center"><font size="4" face="System"> 18:06:38 up 28 days, 2:09, 0 u
sers, load average: 0.00, 0.01, 0.00

</font></p>
</body>
</html>


-----------------------------------------
If you don't want all tags then you can make some filter
to do the work for you.

Well, the solution to this problem is to make a HTMLFilter class.

If you don't have time to do it yourself or just don't know how then you can use this class.

The HTMLFilter class has 2 constructors, one takes an String and the other takes an StringBuffer

Eg. (where str is some HTML code)

HTMLFilter f = new HTMLFilter();
System.out.println(f.filter(str));

The output from www.thegate.nu/uptime.php will
look like

Uptime www.thegate.nu 18:40:30 up 28 days, 2:43, 0 users, load average: 0.00, 0.01, 0.00


------------------------------------------
public class HTMLFilter
{

public String filter(StringBuffer input)
{
return new String(privateHelpMethod(new String(input)));
}

public String filter(String input)
{
return new String(privateHelpMethod(input));
}


private String privateHelpMethod(String input)
{

StringBuffer clean = new StringBuffer();
boolean add = true;

for(int i = 0 ; i < input.length() ; i++)
{

if(input.charAt(i) == '<')
add = false;

else if(input.charAt(i) == '>')
add = true;

else if(add == true)
{
clean.append(input.charAt(i));
}

}

return new String(clean);
}


}
------------------------------------------

Easy but still very useful
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top