2011-11-18 25 views
3

是否有任何庫或預先編寫的代碼從HTML代碼中刪除css屬性。在java中從HTML中刪除css信息

要求是,Java代碼必須通過輸入html文檔進行解析,並移除css屬性並生成輸出html文檔。

例如,如果輸入HTML文檔有這個元素,

 <p class="abc" style="xyz" > some text </p> 

輸出應該是

 <p > some text </p> 

回答

9

使用js oup和NodeTraversor從所有元素中刪除類和樣式屬性

Document doc = Jsoup.parse(input); 


NodeTraversor traversor = new NodeTraversor(new NodeVisitor() { 

    @Override 
    public void tail(Node node, int depth) { 
    if (node instanceof Element) { 
     Element e = (Element) node; 
     e.removeAttr("class"); 
     e.removeAttr("style"); 
    } 
    } 

    @Override 
    public void head(Node node, int depth) {   
    } 
}); 

traversor.traverse(doc.body()); 
String modifiedHtml = doc.toString(); 
+1

Jsoup很棒。 –

0

你可以使用Cyberneko解析文檔,並添加一個簡單的filter,看起來像這個:

public class RemoveStyleFilter 
    extends DefaultFilter 
{ 
    @Override 
    public void startElement(QName element, XMLAttributes attributes, Augmentations augs) 
    throws XNIException 
    { 
    for (String forbidden : new String[] {"class", "style"}) 
    { 
     int index = attributes.getIndex(forbidden); 
     if (index >= 0) 
     { 
     attributes.removeAttributeAt(index); 
     } 
    } 
    super.startElement(element, attributes, augs); 
    } 
}