2007-08-27
javaHTML页面解析的问题
前一段时间工作需要要开发一个网站静态发布的项目,服务建立于weblogic服务器上,为了比较通用,较好的方法是解析html页面上的相关资源,而aspx有较好的domparser可以支持页面的解析,而java本省的dompaser仅仅能解析xml格式的流,网上搜索找到了一个比较好的java工具,CyberNeko HTML Parser,通过这个包可以顺利的解析出页面中的资源。
项目需要以多站点发布的方式实现网站发布的功能,且不能依附其他的服务器实现。这样通用的很多门户网站的资源服务器方式的全路径资源发布这种解决方法无法满足。剩下方法只有解析html获取所需的相应资源。对比了现在比较流行的html解析工具。我们选择了CyberNeko HTML Parser。其实Swing只带有一个HTMLEditorKit,解析文本的能力还很强。但是CyberNeko 的纯xml解析方式正是我们需要的。可以方便的拿到页面相应节点的相应属性。相应的实现可以参考CyberNeko 的网站。基本可以拷下来重用。而拿到这些后,我们通过一个servlet实现对外的封装。这样只需传一个对应文章的id即可获取到这个文章相应资源的对应xml文件(用xmlbean实现)。核心代码如下:
java 代码
- public void ResovlehtmlTag(Node node, boolean isgetfile) throws Exception {
- String[] tags ={"img","table"};//关注的资源节点
- String[] fileds = {"src","backgroud"};//关注的属性
- for (int col = 0; col < tags.length; col++) {
- if (tags[col].equalsIgnoreCase(node.getNodeName())) {
- StringBuffer linkText = new StringBuffer();
- getText(linkText, node);
- NamedNodeMap attrs = node.getAttributes();
- String target = null;
- for (int i = 0; i < attrs.getLength(); i++) {
- if (fileds[col].equalsIgnoreCase(attrs.item(i)
- .getNodeName())) {
- // 在DOM树中,属性是一个结点。
- target = attrs.item(i).getNodeValue();
- target=new String(target.getBytes("ISO8859-1"),"GBK");
- FilterResourcesrc(target, isgetfile);
- break;
- }
- }
- if (target != null)
- System.out.println(target);
- }
- }
- }
- private static void getText(StringBuffer sb, Node node) {
- if (node.getNodeType() == Node.TEXT_NODE) {
- // 取得结点值,即开始与结束标签之间的信息
- sb.append(node.getNodeValue());
- }
- NodeList children = node.getChildNodes();
- if (children != null) {
- int len = children.getLength();
- for (int i = 0; i < len; i++) {
- getText(sb, children.item(i));// 递归遍历DOM树
- }
- }
- }
- private void getResourceValue(Node node, boolean isgetfile)
- throws Exception {
- //if (node.getNodeType() == Node.ELEMENT_NODE)
- ResovlehtmlTag(node, isgetfile);
- for (Node child = node.getFirstChild(); child != null; child = child
- .getNextSibling())
- getResourceValue(child, isgetfile);
- }


评论