Automatically convert Style Sheets to inline style

前端 未结 11 669
说谎
说谎 2020-12-07 14:04

Don\'t have to worry about linked style or hover style.

I want to automatically convert files like this



"
                + "

...

"; // Document doc = Jsoup.connect("http://mypage.com/inlineme.php").get(); 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(), delims = "{}"; StringTokenizer st = new StringTokenizer(styleRules, delims); while (st.countTokens() > 1) { String selector = st.nextToken(), properties = st.nextToken(); 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(); } System.out.println(doc);// now we have the result html without the // styles tags, and the inline css in each // element } private static String concatenateProperties(String oldProp, String newProp) { oldProp = oldProp.trim(); if (!newProp.endsWith(";")) newProp += ";"; return newProp + oldProp; // The existing (old) properties should take precedence. } }

提交回复
热议问题