前一段时间工作需要要开发一个网站静态发布的项目,服务建立于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 代码
  1. public void ResovlehtmlTag(Node node, boolean isgetfile) throws Exception {   
  2.         String[] tags ={"img","table"};//关注的资源节点   
  3.         String[] fileds = {"src","backgroud"};//关注的属性   
  4.         for (int col = 0; col < tags.length; col++) {   
  5.             if (tags[col].equalsIgnoreCase(node.getNodeName())) {   
  6.                 StringBuffer linkText = new StringBuffer();   
  7.                 getText(linkText, node);   
  8.   
  9.                 NamedNodeMap attrs = node.getAttributes();   
  10.                 String target = null;   
  11.                 for (int i = 0; i < attrs.getLength(); i++) {   
  12.                     if (fileds[col].equalsIgnoreCase(attrs.item(i)   
  13.                             .getNodeName())) {   
  14.                         // 在DOM树中,属性是一个结点。   
  15.                         target = attrs.item(i).getNodeValue();   
  16.                         target=new String(target.getBytes("ISO8859-1"),"GBK");   
  17.                         FilterResourcesrc(target, isgetfile);   
  18.                         break;   
  19.                     }   
  20.                 }   
  21.                 if (target != null)   
  22.                     System.out.println(target);   
  23.   
  24.             }   
  25.         }   
  26.     }   
  27.   
  28.     private static void getText(StringBuffer sb, Node node) {   
  29.         if (node.getNodeType() == Node.TEXT_NODE) {   
  30.             // 取得结点值,即开始与结束标签之间的信息   
  31.             sb.append(node.getNodeValue());   
  32.         }   
  33.         NodeList children = node.getChildNodes();   
  34.         if (children != null) {   
  35.             int len = children.getLength();   
  36.             for (int i = 0; i < len; i++) {   
  37.                 getText(sb, children.item(i));// 递归遍历DOM树   
  38.             }   
  39.         }   
  40.     }   
  41.   
  42.     private void getResourceValue(Node node, boolean isgetfile)   
  43.             throws Exception {   
  44.         //if (node.getNodeType() == Node.ELEMENT_NODE)   
  45.             ResovlehtmlTag(node, isgetfile);   
  46.            
  47.         for (Node child = node.getFirstChild(); child != null; child = child   
  48.                 .getNextSibling())   
  49.             getResourceValue(child, isgetfile);   
  50.   
  51.     }   
评论
dearsuper 2007-09-03
技术专家!
发表评论

您还没有登录,请登录后发表评论