package com.enterprise.common;
import java.util.ArrayList;
import java.util.List;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.HtmlPage;
//相关jar htmlexer.jar htmlparser.jar
public class TestDemo {
public static NodeList parserHtmlNodes(String html, String encode, String tagname, String tagArr, String tagArrValue)
{
if ((html == null) || (html.equals(""))) {
return null;
}
Parser parser = Parser.createParser(html, encode);
HtmlPage page = new HtmlPage(parser);
try
{
parser.visitAllNodesWith(page);
List<LinkTag> tags = new ArrayList();
NodeList nodelist = page.getBody();
if ((nodelist == null) || (nodelist.size() == 0))
{
html = "<body>" + html + "</body>";
parser = Parser.createParser(html, encode);
parser.visitAllNodesWith(page);
nodelist = page.getBody();
}
if (nodelist != null)
{
NodeList filterList = nodelist.extractAllNodesThatMatch(new TagNameFilter(tagname), true);
if (filterList != null)
{
NodeList list = new NodeList();
int nodeSize = filterList.size();
for (int i = 0; i < nodeSize; i++)
{
TagNode tagNode = (TagNode)filterList.elementAt(i);
String tagNodeArrValue = tagNode.getAttribute(tagArr);
if ((tagNodeArrValue != null) && (tagNodeArrValue.contains(tagArrValue))) {
list.add(tagNode);
}
if ((tagArr != null) && (tagname.equals(tagArr))) {
list.add(tagNode);
}
}
return list;
}
}
}
catch (ParserException ex)
{
// logger.error(ex.getMessage(), ex);
}
return null;
}
public static void main(String[] args)
{
StringBuffer html=new StringBuffer();
html.append("<div class=\"form-unit\"><span>工程项目名称:</span> <input type=\"text\" id=\"sectionName\" readonly=\"readonly\" style=\"width: 266px;\" value=\"罗源口岸通关中心建设项目--装饰部分\"></div>");
html.append("<div class=\"form-unit\"><span>工程项目名称:</span> <input type=\"text\" id=\"sectionNamexxx\" readonly=\"readonly\" style=\"width: 266px;\" value=\"电饭锅电饭锅\"></div>");
//获取符合要求的节点
NodeList nodeList = TestDemo.parserHtmlNodes(html.toString(),"UTF-8", "input","type","text");
// System.out.println(nodeList.toHtml());
StringBuffer desBuffer =new StringBuffer(html);
// desNodeList.toNodeArray()
if (nodeList != null) {
int nodeSize = nodeList.size();
for (int j = 0; j < nodeSize; j++) {
TagNode tag = (TagNode) nodeList.elementAt(j);
String value = tag.getAttribute("value");
String tagStr=tag.toHtml();
String pStr= "<p style=\"font-weight:700; \">"+value+"</p>";
desBuffer.replace(desBuffer.indexOf(tagStr), desBuffer.indexOf(tagStr)+tagStr.length(), pStr);
}
}
System.out.println(desBuffer.toString());
}
}