繁体   English   中英

使用HTML内联外部CSS

[英]Inline external CSS with HTML

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

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

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

谢谢

你可以试试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();

我对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,}", " ");
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM