【发布时间】:2017-01-06 23:15:02
【问题描述】:
如何使用 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,}", " ");
}
对此有何建议?
【问题讨论】: