使用HTML内联外部CSS

时间:2012-11-09 11:48:32

标签: java html css parsing jstyleparser

我正在寻找一个java库,它可以基于其ID /类属性在内部CSS文件内嵌HTML文档。

我找到了jStyleParser,但我不确定这是否适合我。我似乎无法理解它是否能够完成从HTML中对元素进行内联CSS的工作。文档和示例不是我所期望的。

是否有人可以回答这个问题,或者是否存在其他库?

由于

2 个答案:

答案 0 :(得分:10)

您可以尝试CSSBox。只需查看包中包含的 ComputeStyles 演示(有关运行演示的信息,请参阅分发包中的 doc / examples / README 文件)。它计算所有样式并使用相应的内联样式定义创建一个新的HTML文档(由DOM表示)。

源代码位于 src / org / fit / cssbox / demo / ComputeStyles.java 中,它非常简短。实际上,它使用jStyleParser来完成主要工作,CSSBox只为它提供了一个更好的界面。

        //Open the network connection 
        DocumentSource docSource = new DefaultDocumentSource(args[0]);

        //Parse the input document
        DOMSource parser = new DefaultDOMSource(docSource);
        Document doc = parser.parse();

        //Create the CSS analyzer
        DOMAnalyzer da = new DOMAnalyzer(doc, docSource.getURL());
        da.attributesToStyles(); //convert the HTML presentation attributes to inline styles
        da.addStyleSheet(null, CSSNorm.stdStyleSheet(), DOMAnalyzer.Origin.AGENT); //use the standard style sheet
        da.addStyleSheet(null, CSSNorm.userStyleSheet(), DOMAnalyzer.Origin.AGENT); //use the additional style sheet
        da.getStyleSheets(); //load the author style sheets

        //Compute the styles
        System.err.println("Computing style...");
        da.stylesToDomInherited();

        //Save the output
        PrintStream os = new PrintStream(new FileOutputStream(args[1]));
        Output out = new NormalOutput(doc);
        out.dumpTo(os);
        os.close();

        docSource.close();

答案 1 :(得分:4)

我对JSoup(v1.5.2)感到非常满意。我有这样的方法:

 public static String inlineCss(String html) {
    final String style = "style";
    Document doc = Jsoup.parse(html);
    Elements els = doc.select(style);// to get all the style elements
    for (Element e : els) {
      String styleRules = e.getAllElements().get(0).data().replaceAll("\n", "").trim();
      String delims = "{}";
      StringTokenizer st = new StringTokenizer(styleRules, delims);
      while (st.countTokens() > 1) {
        String selector = st.nextToken(), properties = st.nextToken();
        if (!selector.contains(":")) { // skip a:hover rules, etc.
          Elements selectedElements = doc.select(selector);
          for (Element selElem : selectedElements) {
            String oldProperties = selElem.attr(style);
            selElem.attr(style,
                oldProperties.length() > 0 ? concatenateProperties(
                    oldProperties, properties) : properties);
          }
        }
      }
      e.remove();
    }
    return doc.toString();
  }

  private static String concatenateProperties(String oldProp, @NotNull String newProp) {
    oldProp = oldProp.trim();
    if (!oldProp.endsWith(";"))
      oldProp += ";";
    return oldProp + newProp.replaceAll("\\s{2,}", " ");
  }