我在尋找一個java庫,它可以根據ID/class屬性將內部CSS
文件與HTML
文檔內聯。我發現了jStyleParser,但我不確定這是否適合我。我似乎無法理解它是否可以完成內聯元素CSS
的工作。文檔和示例不是我所期望的。HTML內嵌外部CSS
有沒有人可以回答這個問題,或者是否存在另一個庫?
謝謝
我在尋找一個java庫,它可以根據ID/class屬性將內部CSS
文件與HTML
文檔內聯。我發現了jStyleParser,但我不確定這是否適合我。我似乎無法理解它是否可以完成內聯元素CSS
的工作。文檔和示例不是我所期望的。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,}", " ");
}
我認爲你缺少'concatenateProperties'功能:) – zozelfelfo
感謝@zozelfelfo - 我說從山魈缺少的功能 –
切換到亞馬遜SES - 你救了我的一天:) 山魈這是否內聯本身 – jang00
Ack!它在AppEngine中不起作用!詛咒你的谷歌! – Chloe
@radkovo如果源是String input =「 ...」(而不是URL),這個示例如何修改?很好的工作順便! – athspk
@athspk您將不得不編寫自己的DocumentSource實現,該實現從字符串而不是URL創建輸入流。這應該很簡單,只需看看最初的DefaultDocumentSource實現。 [Here](http://stackoverflow.com/questions/247161/how-do-i-turn-a-string-into-a-stream-in-java)你可能會發現如何從一個字符串創建一個輸入流。 – radkovo