java - 如何将外部 CSS 添加到 HTML 'style'

标签 java html css jsoup

如何使用 Java 将外部 CSS 样式表转换为我的 HTML 的“样式”部分?

我希望能够将我的外部 CSS 存在于“样式”部分中,以便我可以将其解析为内联样式而不是外部样式,我见过的最简单的方法是将 CSS 直接放在HTML 而不是链接。

我想在我的 HTML 中更改它:

<link rel="stylesheet" href="smartdoc.css" /> 

为此(理想情况下通过将 CSS 文件作为参数传递给方法):

<style>
    Content from external CSS.
</style>

这样我就可以使用 JSoup 将其转换为内联样式,使用如下方式:

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

对此有什么建议吗?

最佳答案

我假设您的所有文件都在以 UTF-8 编码的本地硬盘驱动器上。

dummy.html

<link rel="stylesheet" href="smartdoc.css" />

smartdoc.css

a {
  background-color: red;
}

p {
  background-color: green;
}

示例代码

要用 CSS 文件内容替换 link 节点,请执行以下操作:

// Load HTML file
String charsetName = "UTF-8";
Document doc = Jsoup.parse(new File("dummy.html"), charsetName);
System.out.println("BEFORE:\n" + doc.outerHtml());

// Replace each link nodes with its respective CSS file content
for (Element link : doc.select("link[rel=stylesheet]")) {
    String cssFilename = link.attr("href");

    Element style = new Element(Tag.valueOf("style"), "");
    style.appendText("/* " + cssFilename + " */");
    style.appendText(loadCssFileContent(cssFilename, charsetName));

    link.replaceWith(style);
}

System.out.println("\nAFTER:\n" + doc.outerHtml());

private static String loadCssFileContent(String path, String charsetName) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, charsetName);
}

输出

BEFORE:
<html>
 <head>
  <link rel="stylesheet" href="smartdoc.css">
 </head>
 <body></body>
</html>

AFTER:
<html>
 <head>
  <style>/* smartdoc.css */a { background-color: red; } p { background-color: green; }</style>
 </head>
 <body></body>
</html>

关于java - 如何将外部 CSS 添加到 HTML 'style',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39231391/

相关文章:

php - 为动态创建的 div 设置一个附加类

html - 如何使用 css 和 html 制作页脚网格?

java - 使用腻子时出现"Error: Invalid port number"

JavaFX 和 Java 互操作性

html - Linux服务器根文件夹

html - 选择每个第一个和第四个(最后一个)div

css - 如何使 ng-select 删除和只读

java - 第二次单击时更改 actionListener (actionPerformed)

java - 从嵌套内部类访问外部内部类

jquery - 侧边栏应该 float 在移动设备的顶部 - 但不是在桌面上