繁体   English   中英

如何从Java中的html标记中删除属性

[英]how to remove attribute from html tags in java

我想从定位标记中删除特定属性:

<a  id="nav-askquestion" style="cursor:default" href="/questions">

输出: -

<a   href="/questions">

通过java程序

我们将htmlparser用于此类工作

您可以使用以下未经测试的片段来解析和修改节点:

NodeVisitor visitor = new NodeVisitor() {
    public void visitTag(Tag tag) {
            tag.removeAttribute("id");
            tag.removeAttribute("style");
    }

};

Parser parser = new Parser(...);
parser.visitAllNodesWith(visitor);

这个小片段可以解决问题。

问我是否需要有关正则表达式的问题


public class test {

    public static void main(String[] args) {
        String htmlFragment ="<a  id=\"nav-askquestion\" style=\"cursor:default\" href=\"/questions\">";
        String attributesToRemove = "id|style";

        System.out.println(htmlFragment);
        System.out.println(cleanHtmlFragment(htmlFragment, attributesToRemove));
    }

    private static String cleanHtmlFragment(String htmlFragment, String attributesToRemove) {
        return htmlFragment.replaceAll("\\s+(?:" + attributesToRemove + ")\\s*=\\s*\"[^\"]*\"","");    
    }
}

人们可能会建议使用正则表达式,但是请注意 ,您可以使用XML Parser。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM