论坛首页 Java企业应用论坛

Htmlparser 得到替换后的文本

浏览 2724 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-02-05   最后修改:2010-02-05
需求:替换HTML文件内的全部链接然后得到替换后的HTML文件

考虑采用Htmlparser解析

代码如下

public class DoReplaceHtmlHref implements Callable<String> {

		private String content;

		public DoReplaceHtmlHref(String content) {
			this.content = content;
		}

		public String call() throws Exception {
			Parser myParser = new Parser();
			StringBuffer sbContent = new StringBuffer();

			try {
				myParser.setInputHTML(content);

				//得到页面的所的节点集合
				NodeList nodes = myParser
						.extractAllNodesThatMatch(new NodeFilter() {
							public boolean accept(Node node) {
								return true;
							}
						});

				for (int i = 0; i < nodes.size(); i++) {
					Node node = nodes.elementAt(i);
					//如果为链接节点
					if (node instanceof LinkTag) {
						LinkTag linkTag = (LinkTag) node;
						//设置此链接节点的内容
						sbContent.append("<a href=www.163.com>");			} else if (node instanceof TextNode) {
						//如果为文本节点直接获取内容
						TextNode text = (TextNode) node;
						sbContent.append(text.getText());
					} else {
						//如果为其他节点在文本两端加上<>
						sbContent.append('<');
						sbContent.append(node.getText());
						sbContent.append('>');
					}
				}
			} catch (Exception e) {
				log.error("parse html enode is error");
			}
			return sbContent.toString();
		}

	}
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics