How to remove the object tag from my HTML using Java
Hi I am trying to remove the object tag from my开发者_如何学Python HTML content using Java so that I can render the HTML in devices which do not support Flash
<object classid="clsid:F08DF954-8592-11D1-B16A-00C0F0283628" id="Slider1" width="100" height="50">
<param name="BorderStyle" value="1" />
<param name="MousePointer" value="0" />
<param name="Enabled" value="1" />
<param name="Min" value="0" />
<param name="Max" value="10" />
</object>
This regex must do the trick:
<\/?object(\s\w+(\=\".*\")?)*\>
You could just use Tagsoup (http://ccil.org/~cowan/XML/tagsoup/), which is an xml parser which can read from html, even if badly formatted (doesn't need to be xhtml or even conform).
You then can just remove all object tags using xpath.
This is much safer than a regex, which is difficult to maintain if you want to master all edge cases.
The OBJECT
HTML element may be nested. Since Java does not provide a native regex recursive expression, you cannot directly match an outermost OBJECT
element with a single regex. You can, however, craft a regex to match an innermost OBJECT
element, and iterate, replacing them from the "inside-out" until there are none left. Here is a tested Java snippet which does precisely that:
String regex = "<object\\b[^>]*>[^<]*(?:(?!</?object\\b)<[^<]*)*</object\\s*>";
String resultString = null;
java.util.regex.Pattern p = java.util.regex.Pattern.compile(
regex,
java.util.regex.Pattern.CASE_INSENSITIVE |
java.util.regex.Pattern.UNICODE_CASE);
java.util.regex.Matcher m = p.matcher(subjectString);
while (m.find())
{ // Iterate until there are no OBJECT elements.
resultString = m.replaceAll("");
m = p.matcher(resultString);
}
System.out.println(resultString);
CAVEATS: As many will undoubtedly point out: "You can't parse HTML with regex!" And they are correct (if your solution must work reliably 100% of the time). Although the solution above will work for a lot of cases, be aware that it has some limitations and there are certain things which can trip it up, namely:
- An
"<OBJECT...>"
start or"</OBJECT>"
end tag may not appear in anyCDATA
strings such as in SCRIPT or STYLE tags, or within any tag attribute, or within any HTML comment. e.g.<p title="evil <OBJECT> attribute">
or<SCRIPT>alert("Bad <OBJECT> script here!");</SCRIPT>
, or<!-- <OBJECT> inside a comment -->
. - The
<OBJECT>
start tag may not contain any angle brackets in its attributes.
These special cases should be pretty rare and the code above should work just fine for most (if not all) HTML files you have lying around.
精彩评论