使用HTML内联外部CSS

jan*_*ann 7 html css java parsing jstyleparser

我正在寻找一个java库,它可以CSS使用HTML基于其ID /类属性的文档内联外部文件.

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

是否有人可以回答这个问题,或者是否存在另一个图书馆?

谢谢

rad*_*ovo 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();
Run Code Online (Sandbox Code Playgroud)

  • 确认!它在 AppEngine 中不起作用!诅咒你谷歌! (2认同)

Nic*_*ell 5

我对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,}", " ");
  }
Run Code Online (Sandbox Code Playgroud)